MySQL:单个查询,仅显示两个表中不存在id的行

时间:2010-12-13 17:49:22

标签: mysql sql

鉴于以下两个表,如何编写单个查询,仅显示两个表中不存在id的行?

table_one
--------------
id    | name
4     | Jack
5     | John
6     | Henry
8     | Frank
9     | Bob
table_two
--------------
id    | name
4     | Jack
6     | Henry
8     | Frank

运行查询后的输出:John Bob

2 个答案:

答案 0 :(得分:2)

假设您的意思是“存在于一个表或另一个表中,但不存在于两个表中” - 您使用子查询和联合选择!

    SELECT name FROM table_one WHERE id NOT IN (SELECT id FROM table_two) 
UNION SELECT name from table_two WHERE id NOT IN (SELECT id FROM table_one);

此外,如果您希望将这些结果分组为单个结果行:

SELECT group_concat(x.name) FROM 
  (SELECT name FROM table_one 
      WHERE id NOT IN (SELECT id FROM table_two) 
   UNION SELECT name from table_two 
       WHERE id NOT IN (SELECT id FROM table_one)) as x;

答案 1 :(得分:0)

如果MySQL有一个FULL OUTER JOIN运算符,这将很简单:这样的连接为每个表中的每个记录返回一行,如果两边都存在记录则加入ID,不存在的那边是NULL如果不。然后你可以在连接的两边做同样的检查@ajreal建议。

相反,你可以UNION LEFT和RIGHT JOIN的结果......

SELECT table_one.name
FROM table_one
LEFT JOIN table_two ON table_one.id = table_two.id
WHERE table_two.id IS NULL
UNION
SELECT table_two.name
FROM table_one
RIGHT JOIN table_two ON table_one.id = table_two.id
WHERE table_one.id IS NULL