MySQL:如何在两个表中找到不存在的值?

时间:2013-01-28 13:42:11

标签: mysql sql

  

可能重复:
  MySQL - How to get a list of values in Table A that don’t exist in Table B?

我有三张桌子。

表x:

+------+
| ID   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+

表Y

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

表Z

+------+
| ID   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    6 |
|    7 |
+------+

我必须找到TABLE Z中存在的值,但表X and Y中不存在该值。

输出:

+----+
| ID |
------
| 6  |
| 7  |
+----+

我怎么能得到这个?

4 个答案:

答案 0 :(得分:1)

SELECT z.ID 
FROM TableZ z
LEFT JOIN TableX x on x.ID = z.ID
LEFT JOIN TableY y on y.Id = z.ID
WHERE x.Id IS NULL 
AND y.ID IS NULL

sqlFiddle(与Xavi Lopez和我一起,都给出相同的结果)

答案 1 :(得分:1)

您可以使用EXISTS制作子查询。

SELECT tz.id 
FROM Z tz 
WHERE 
    NOT EXISTS (select 1 from X tx where tx.id = tz.id)
    AND NOT EXISTS (select 1 from Y ty where ty.id = tz.id)
但是,

@RaphaëlAlthaus's answer可能会提高效率。见Can I get better performance using a JOIN or using EXISTS?

MySQL参考有一个关于EXISTS的部分:13.2.9.6. Subqueries with EXISTS or NOT EXISTS

答案 2 :(得分:0)

SELECT  a.ID
FROM    tableZ a
        LEFT JOIN
        (
            SELECT ID FROM tableX
            UNION 
            SELECT ID FROM tableY
        ) b ON a.ID = b.ID
WHERE   b.ID IS NULL

答案 3 :(得分:0)

你可以使用减号功能

SELECT * FROM Z
MINUS
(
SELECT * FROM Y
UNION
SELECT * FROM X
)