简体   繁体   English

如果另一个表中存在ID,则插入行

[英]Insert row if ID exists in another table

I wanted to check if there was a way to insert a row, but only if a ID already existed in another table. 我想检查是否有插入行的方法,但前提是另一个表中已经存在一个ID。 For example: 例如:

INSERT INTO table1 (carID) 
SELECT carID FROM table2 WHERE table1.carID IN table2.carID

Basically, I only would like to insert carID in table1 if that ID can be found in table2. 基本上,我只想在table1中找到carID才能插入该ID。

Try using EXISTS : 尝试使用EXISTS

INSERT INTO table1 (carID)
SELECT t2.carID
FROM table2 t2
WHERE EXISTS (SELECT 1 FROM table1 t1 WHERE t1.carID = t2.carID);

You can add to table1 all carID s that exist in table2 : 您可以将table2中存在的所有carID添加到table1

INSERT INTO table1 (carID) 
SELECT carID FROM table2

If you want to apply a condition you can add a WHERE part. 如果要应用条件,则可以添加WHERE零件。

you could use in 你可以用in

    INSERT INTO table1 (carID) 
    SELECT carID FROM table2 WHERE table2.carID IN (select carID from table1 where carID is not null)

You could just select the ID from table2 checking for the given ID in the WHERE clause. 您可以从table2选择ID,然后检查WHERE子句中的给定ID。 If there is no matching row in table2 , the SELECT returns the empty set and nothing is inserted into table1 . 如果table2没有匹配的行,则SELECT返回空集,并且没有任何内容插入table1 If there are rows with that ID, they get selected and inserted. 如果存在具有该ID的行,则将其选中并插入。 If an ID can occurs multiple times in table2 but you only want to insert it once, you can use DISTINCT . 如果一个ID在table2可以出现多次,但您只想插入一次,则可以使用DISTINCT

INSERT INTO table1
            (carid) 
            SELECT DISTINCT
                   carid
                   FROM table2
                        WHERE carid = <given carid>;

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

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