如果数据不存在,子查询将数据插入查找 table

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

我想将两个 table 的主键插入到查找 table 中。如果从 table 中返回的数据不存在于 table 中,我如何 插入该数据? IE。如果查询 returns 1,1 和 1,1 已经存在于 table 中,则不要插入。我的查询如下所示:

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

谢谢!

您可以使用 NOT EXISTS 检查数据是否已经存在于 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);