我想将两个表中的主键插入查找表。如果仅插入表中返回的数据(如果表中尚不存在)?即如果查询返回1,1并且表中已存在1,1,请不要插入。我的查询如下:
INSERT INTO tblUserLookup(name,class)
SELECT tblName.id,tblClass.id FROM tblName,tblClass
WHERE name='bob' AND class='grade4';
谢谢!
答案 0 :(得分:0)
您可以使用NOT EXISTS检查表格中是否已存在数据
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);