[英]Insert row if ID exists in another table
我想检查是否有插入行的方法,但前提是另一个表中已经存在一个ID。 例如:
INSERT INTO table1 (carID)
SELECT carID FROM table2 WHERE table1.carID IN table2.carID
基本上,我只想在table1中找到carID才能插入该ID。
尝试使用EXISTS
:
INSERT INTO table1 (carID)
SELECT t2.carID
FROM table2 t2
WHERE EXISTS (SELECT 1 FROM table1 t1 WHERE t1.carID = t2.carID);
您可以将table2
中存在的所有carID
添加到table1
:
INSERT INTO table1 (carID)
SELECT carID FROM table2
如果要应用条件,则可以添加WHERE
零件。
你可以用in
INSERT INTO table1 (carID)
SELECT carID FROM table2 WHERE table2.carID IN (select carID from table1 where carID is not null)
您可以从table2
选择ID,然后检查WHERE
子句中的给定ID。 如果table2
没有匹配的行,则SELECT
返回空集,并且没有任何内容插入table1
。 如果存在具有该ID的行,则将其选中并插入。 如果一个ID在table2
可以出现多次,但您只想插入一次,则可以使用DISTINCT
。
INSERT INTO table1
(carid)
SELECT DISTINCT
carid
FROM table2
WHERE carid = <given carid>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.