我有以下表格:
Contacts
contact_id, contact_name, etc.
assigned_lists
contact_id, list_id
每个联系人可以与多个列表关联,该列表存储在assigned_lists
列中。
我有很多与任何列表无关的联系人。我如何将所有contact_id
与列表无关的 's 插入到 's 中assigned_lists
?
尝试:
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
)
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
你可以试试下面
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 in 子句具有性能优势。
可以在此处找到有关相同内容的详细说明NOT IN vs NOT EXISTS