MySQL5查询帮助查找非验证的连接行

时间:2013-02-17 14:52:44

标签: mysql sql join

在下面找到测试表:

SELECT * FROM tbl_emp; // There must be few employee with no dept id (did)
+------+-------+------+
| eid  | ename | did  |
+------+-------+------+
|    1 | SCOTT |    2 |
|    2 | JAMES |    4 |
|    3 | BOND  |    1 |
|    4 | TIGER |    5 |
|    5 | CHIP  |    0 |
|    6 | DALE  |    0 |
|    7 | MARY  |    0 |
+------+-------+------+

SELECT * FROM tbl_dept;// There must be few depts which have no employee.
+-------+-------------+
| dptid | dname       |
+-------+-------------+
|     1 | HR          |
|     2 | IT          |
|     3 | ADMIN       |
|     4 | TRAVEL      |
|     5 | SALES       |
|     6 | FINANCE     |
|     7 | ENGINEERING |
+-------+-------------+

我想列出tbl_emp中没有dept的所有员工姓名以及来自tbl_dept的所有dname,以下列方式在SINGLE QUERY中没有员工:

DESIRED RESULTSET:
-------------------
ename  dname
CHIP    
DALE
MARY
       ADMIN
       FINANCE
       ENGINEERING
-------------------

我所能做的就是:

SELECT ename FROM tbl_emp WHERE did NOT IN (SELECT dptid FROM tbl_dept);

SELECT dname FROM tbl_dept WHERE dptid NOT IN (SELECT did FROM tbl_emp);

请帮助同时选择dname和ename以及单个查询。

1 个答案:

答案 0 :(得分:0)

您可以使用UNION

SELECT ename, NULL dname 
FROM tbl_emp 
WHERE did NOT IN (SELECT dptid FROM tbl_dept)
UNION
SELECT NULL ename, dname 
FROM tbl_dept 
WHERE dptid NOT IN (SELECT did FROM tbl_emp);

更新1

你也可以使用LEFT JOIN而不是NOT IN我宁愿使用这个

SELECT  a.ename, b.dname 
FROM    tbl_emp a 
        LEFT JOIN tbl_dept b
            ON a.did = b.dptid
WHERE   b.dptid IS NULL
UNION
SELECT  c.ename, d.dname 
FROM    tbl_dept d 
        LEFT JOIN tbl_emp c
            ON d.dptid = c.did
WHERE   c.did IS NULL