简体   繁体   中英

Subquery to insert data into lookup table if it doesn't already exist

I want to insert the primary keys from two tables into a lookup table. How do I only insert the data returned from the tables if it does not already exist in the table? Ie if the query returns 1,1 and 1,1 already exists in the table, don't insert. My query looks like this:

INSERT INTO tblUserLookup(name,class)
SELECT tblName.id,tblClass.id FROM tblName,tblClass
WHERE name='bob' AND class='grade4';

Thanks!

You can use NOT EXISTS to check if data is already existed in the table

INSERT INTO tblUserLookup(name,class)
select idName, idClass 
from (SELECT tblName.id idName,tblClass.id idClass FROM tblName,tblClass
      WHERE name='bob' AND class='grade4') tmp
where not exists (select name from tblUserLookup tmp1
               where tmp1.name = tmp.idName and tmp1.class = tmp.idClass);

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