问题描述
我有两个表:
people
| peopleID | Lastname | Firstname |
| -------- | -------- | --------- |
| 1 | Smith | Marc |
| 2 | Doe | John |
| 3 | Davidson | Terry |
| 4 | Meyer | Todd |
| 5 | Richards | Abe |
customers
| customerID | Lastname | Company |
| ---------- | -------- | ------------------- |
| 1 | Davidson | Wonderproducts Inc. |
| 2 | Meyer | Banana Inc. |
现在,我想将表people
的所有元素插入到表customers
中,除了那些姓氏等于customers
中姓氏的元素。
因此,customers
的结尾应如下所示:
| customerID | Lastname | Company |
| ---------- | -------- | ------------------- |
| 1 | Davidson | Wonderproducts Inc. |
| 2 | Meyer | Banana Inc. |
| 3 | Smith | |
| 4 | Doe | |
| 5 | Richards | |
我已经尝试过解决这个问题:
IF NOT EXISTS
(SELECT 1 FROM customers WHERE Lastname = (SELECT Lastname FROM people))
INSERT INTO customers (Lastname) VALUES (SELECT Lastname FROM people)
解决方法
尝试一下
INSERT INTO customers (Lastname)
SELECT P.Lastname
FROM people P
LEFT JOIN customers C ON C.Lastname = P.Lastname
WHERE C.customerID IS NULL