从表中添加行,而不是在另一个表中

时间:2013-06-29 00:20:58

标签: sql tsql

我有以下表格:

Contacts
      contact_id, contact_name, etc.
assigned_lists
      contact_id, list_id

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

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

3 个答案:

答案 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