Postgres。插入多行不存在的行
我有像 (
这样的对,并且我有具有以下结构的表:
_____________________________________
| id | first_column | second_column |
我需要插入所有尚不存在的对。 我认为我需要类似 INSERT IF NOT EXIST
但对于每一对。
我尝试使用此代码:
INSERT INTO <table_name>(<first_column>, <second_column>)
VALUES (CASE
WHEN NOT EXISTS (
SELECT 1
FROM <table_name>
WHERE <first_column> = <pair_1_value_1> AND <second_column> = <pair_1_value_2>
) THEN (<pair_1_value_1>, <pair_1_value_2>)
WHEN NOT EXISTS (
SELECT 1
FROM <table_name>
WHERE <first_column> = <pair_2_value_1> AND <second_column> = <pair_2_value_2>
) THEN (<pair_2_value_1>, <pair_2_value_2>)
.....
END
);
但出现此错误:INSERT 的目标列多于表达式
。另外,我认为它不起作用,因为它只会插入第一个通过条件的一行。作为其他编程语言中的 if - elif - else
运算符
I have pairs like (<first_value>, <second_value>)
and I have table with following structure:
_____________________________________
| id | first_column | second_column |
I need to insert all pairs which do not exist already.
I think that I need something like INSERT IF NOT EXIST
but for every pair.
I try use this code:
INSERT INTO <table_name>(<first_column>, <second_column>)
VALUES (CASE
WHEN NOT EXISTS (
SELECT 1
FROM <table_name>
WHERE <first_column> = <pair_1_value_1> AND <second_column> = <pair_1_value_2>
) THEN (<pair_1_value_1>, <pair_1_value_2>)
WHEN NOT EXISTS (
SELECT 1
FROM <table_name>
WHERE <first_column> = <pair_2_value_1> AND <second_column> = <pair_2_value_2>
) THEN (<pair_2_value_1>, <pair_2_value_2>)
.....
END
);
But I get this error: INSERT has more target columns than expressions
. Also, I thought it wouldn't work because it would only insert the one line that first passes the condition. As a if - elif - else
operators in other programing languages
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的条件两者都为假,您的查询将尝试将零值插入到两列中。那是不合适的。在这种情况下,您需要插入零行和两列。
SQL中没有
IF
;不要试图模仿它。有WHERE
:在您的实际代码中,最好是:
CREATE TEMP TABLE wtf as SELECT * FROM omg where 0=1
)wtf
CTE)If both your conditions are false, your query attempts to insert zero values into two columns. That is not going to fit. In that case you need to insert zero rows with two columns.
There is no
IF
in SQL; don't try to emulate it. There isWHERE
:In your actual code it is probably better to:
CREATE TEMP TABLE wtf as SELECT * FROM omg where 0=1
)wtf
CTE)MERGE
语句没有完全满足您的需要吗?这个例子似乎按照你所描述的那样工作,至少对我来说:
Doesn't the
MERGE
statement do exactly what you need?This example seems to work as you describe, at least to me: