简体   繁体   English

SQL选择并插入(如果不存在)

[英]SQL select and insert if not exists

I want to make an sql query which can insert into table1. 我想做一个可以插入到table1中的sql查询。 This table references table2 with the table2_id foreign key. 该表使用table2_id外键引用table2。

my sql looks like this so far: 到目前为止,我的sql看起来像这样:

INSERT INTO table1 (table1_id, name, date, table2_id) 
VALUES (1, "somename", "29.04.2014", (SELECT id FROM table 2 WHERE table2.name = "BOB")  )

I also want to insert values into table2 if it cannot find the table2.name and then insert the key for this into table1. 我还想在无法找到table2.name的情况下将值插入table2,然后将其密钥插入table1。

Anyone knows how to do this? 有人知道该怎么做吗?

I would suggest that you use insert . . . select 我建议您使用insert . . . select insert . . . select insert . . . select rather than insert . . . values insert . . . select而不是insert . . . values insert . . . values insert . . . values : insert . . . values

INSERT INTO hovedenhet (organisasjonsnummer, navn, stiftelsesdato, registreringsdatoEnhetsregisteret, organisasjonsform_id) 
    SELECT 813550202, 'SAMEIET SCHWEIGAARDSGATE 21-23', '10.01.2014', '29.04.2014', id
    FROM organisasjonsformhovedenhet oh
    WHERE oh.organisasjonsform = 'BOB';

Your original query will insert the row with a NULL value for the last column, if there is no match. 如果没有匹配项,则原始查询将在最后一列插入具有NULL值的行。 This will not insert anything in that case. 在这种情况下,这不会插入任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM