从表A中选择,表B中不存在

时间:2013-04-08 22:46:18

标签: mysql select

我正在尝试为MySQL编写一个SELECT语句,它从表A中选择表B中不存在的内容。例如:

表A:

+------+
| BAND |
+------+
| 1    |
| 2    |
| 3    |
| 4    |
| 5    |
+------+

表B:

+------+
| HATE |
+------+
| 1    |
| 5    |
+------+

因此,如果表A是所有乐队,而表B是我讨厌的乐队,那么我只想要我不讨厌的乐队。所以选择的结果应该是:

+------+
| BAND |
+------+
| 2    |
| 3    |
| 4    |
+------+

我如何为此写一个选择?这是我的最后一次尝试:

SELECT * FROM A LEFT JOIN B ON A.BAND = B.HATE WHERE B.HATE IS NULL;

编辑:上面的一行已修复!请参阅下面的评论......“= NULL”与“IS NULL”。

4 个答案:

答案 0 :(得分:17)

我会使用连接

select A.*
from A left join B on A.BAND = B.HATE
where B.HATE IS NULL;

记住:为表格创建适当的索引

答案 1 :(得分:6)

您可以使用IN,但效率极低:

SELECT * FROM tableA WHERE id NOT IN (SELECT id FROM tableB)

答案 2 :(得分:0)

SELECT * FROM tableA WHERE id NOT EXISTS (SELECT DISTINCT id FROM tableB)

SELECT * FROM tableA WHERE id NOT EXISTS (SELECT id FROM tableB GROUP BY id)

答案 3 :(得分:-3)

SELECT BAND FROM A WHERE BAND NOT EXISTS(SELECT DISTINCT HATE FROM B)

OR

SELECT BAND FROM A WHERE NOT EXISTS ( SELECT HATE FROM B WHERE A.BAND = B.HATE);