0

我有以下表格:

Contacts
      contact_id, contact_name, etc.
assigned_lists
      contact_id, list_id

每个联系人可以与多个列表关联,该列表存储在assigned_lists列中。

我有很多与任何列表无关的联系人。我如何将所有contact_id与列表无关的 's 插入到 's 中assigned_lists

4

3 回答 3

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
)
于 2013-06-29T00:24:43.717 回答
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

于 2013-06-29T00:34:36.623 回答
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 in 子句具有性能优势。

可以在此处找到有关相同内容的详细说明NOT IN vs NOT EXISTS

于 2013-06-29T02:58:25.673 回答