我有以下表格:
Contacts
contact_id, contact_name, etc.
assigned_lists
contact_id, list_id
每个联系人都可以与多个列表相关联,该列表存储在assigned_lists
列中。
我有很多与任何列表无关的联系人。如何将与列表无关的所有contact_id
插入assigned_lists
?
答案 0 :(得分:3)
尝试:
INSERT INTO assigned_lists (contact_id, list_id)
SELECT contact_id, 24
FROM Contacts
WHERE contact_id NOT IN (
SELECT DISTINCT contact_id
FROM assigned_lists
)
答案 1 :(得分:2)
INSERT INTO assigned_lists (contact_id, list_id)
SELECT contact_id, @yourNewListID
FROM Contacts
WHERE contact_id NOT IN (SELECT contact_id FROM assigned_lists)
SQL小提琴示例:http://sqlfiddle.com/#!3/d59d1e/1
答案 2 :(得分:2)
你可以试试下面的
INSERT INTO assigned_lists (contact_id, list_id)
SELECT contact_id, list_id = 1234
FROM Contacts C
WHERE NOT EXISTS (SELECT 1 FROM assigned_lists A WHERE A.contact_id = C.contact_id )
记住,not exists子句在not子句中具有性能优势。
有关相同内容的详细说明,请参见NOT IN vs NOT EXISTS