在测试表下方找到:
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 |
+-------+-------------+
我想以以下方式在 SINGLE QUERY 中列出 tbl_emp 中没有部门的所有员工姓名和 tbl_dept 中没有员工的所有员工姓名:
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 以及在单个查询中也是如此。