如何从table_1查询具有重复ID的table_2上没有ID的数据。见下面的例子。
我想从表2中获得表1中的ID 5和6
Table 1
-------------
| ID | Name |
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
| 5 | e |
| 6 | f |
-------------
Table 2
-------------
Table 1 ID |
| 1 |
| 1 |
| 2 |
| 2 |
| 2 |
| 3 |
| 4 |
-------------
谢谢!
答案 0 :(得分:2)
使用:
SELECT t.id
FROM TABLE_1 t1
LEFT JOIN TABLE_2 t2 ON t2.id = t1.id
WHERE t2.id IS NULL
使用NOT EXISTS:
SELECT t.id
FROM TABLE_1 t1
WHERE NOT EXISTS(SELECT NULL
FROM TABLE_2 t2
WHERE t2.id = t1.id)
使用NOT IN:
SELECT t.id
FROM TABLE_1 t1
WHERE t1.id NOT IN (SELECT t2.id
FROM TABLE_2 t2)
因为table2的id列中不应该有NULL值,所以LEFT JOIN / IS NULL是最快的意思:http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join-is-null-mysql/
答案 1 :(得分:2)
减号查询会非常有用,请看这个链接:minus query replacement 对于您的数据,这将是这样的:
SELECT table_1.id FROM table_1 LEFT JOIN table_2 ON table_2.id = table_1.id WHERE table_2.id IS NULL
答案 2 :(得分:0)
如果我正确理解你,你想做一个外连接。在这种情况下,它将是:
SELECT * FROM
table_1 LEFT JOIN ON table_2
ON table_1.id = table_2.id
WHERE table_2.id is NULL
答案 3 :(得分:0)
这个可以做你想要的:
Select t1.id
From table1 t1
Left Join table2 t2
On t2.id = t1.id
Where t2.id Is Null
结果:
id
--
5
6