简体   繁体   中英

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. 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.

Try using 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 :

INSERT INTO table1 (carID) 
SELECT carID FROM table2

If you want to apply a condition you can add a WHERE part.

you could use 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. If there is no matching row in table2 , the SELECT returns the empty set and nothing is inserted into table1 . If there are rows with that ID, they get selected and inserted. If an ID can occurs multiple times in table2 but you only want to insert it once, you can use DISTINCT .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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