[英]Insert new row of data in SQL table if the 2 column values do not exist
I have a PostgreSQL table interactions
with columns我有一个 PostgreSQL 表与列的
interactions
AAId, IDId, S, BasicInfo, DetailedInfo, BN
AAID
and IDId
are FK to values referencing other tables. AAID
和IDId
是引用其他表的值的 FK。
There are around 1540 rows in the ID
table and around 12 in the AA
table. ID
表中大约有 1540 行, AA
表中大约有 12 行。
Currently in the interactions
table there are only around 40 rows for the AAId value = 12
I want to insert a row for all the missing IDId
values.目前在
interactions
表中,AAId 值只有大约 40 行AAId value = 12
我想为所有缺失的IDId
值插入一行。
I have searched, but cant find an answer to inserting rows like this.我已经搜索过,但找不到插入这样的行的答案。 I am not overly confident with SQL, I can do basics but this is a little beyond me.
我对 SQL 并不过分自信,我可以做基础,但这有点超出我的能力范围。
To clarify, I want to perform a kind of loop where,澄清一下,我想执行一种循环,其中,
for each IDId from 1-1540,
if (the row with AAId = 12 and IDId(current IDId in the loop does not exist)
insert a new row with,
AAId = 12,
IDId = current IDId in the loop,
S = 1,
BasicInfo = Unlikely
DetailedInfo = Unlikely
Is there a way to do this in SQL? SQL有没有办法做到这一点?
Yes, this is possible.是的,这是可能的。 You can use data from different tables when inserting data to a table in Postgres .
在向 Postgres 中的表插入数据时,可以使用来自不同表的数据。 In your particular example, the following insert should work, as long as you have the correct primary/unique key in
interactions
, which is a combination of AAId
and IDId
:在您的特定示例中,只要您在
interactions
中具有正确的主键/唯一键( AAId
和IDId
的组合),以下插入就应该有效:
INSERT INTO interactions (AAId, IDId, S, BasicInfo, DetailedInfo, BN)
SELECT 12, ID.ID, 1, 'Unlikely', 'Unlikely'
FROM ID
ON CONFLICT DO NOTHING;
ON CONFLICT DO NOTHING
guarantees that the query will not fail when it tries to insert rows that already exist, based on the combination of AAId
and IDId
. ON CONFLICT DO NOTHING
根据AAId
和IDId
的组合,保证查询在尝试插入已经存在的行时不会失败。
If you don't have the correct primary/unique key in interactions
, you have to filter what IDs to insert manually:如果您在
interactions
中没有正确的主键/唯一键,则必须过滤要手动插入的 ID:
INSERT INTO interactions (AAId, IDId, S, BasicInfo, DetailedInfo, BN)
SELECT 12, ID.ID, 1, 'Unlikely', 'Unlikely'
FROM ID
WHERE NOT EXISTS (
SELECT * FROM interactions AS i
WHERE i.AAId = 12 AND i.IDId = ID.ID
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.