我想在没有项目的情况下获取所有员工,没有员工的项目。我不知道我在哪里做错了。
表格结构:
employee:employee_id(PK),employee_name //所有员工
项目:project_code(PK),project_title //所有项目
project_team:project_code(FK),employee_id(FK)//正在使用项目和员工的桥接表。
这是我的疑问:
SELECT *
FROM employee e
LEFT JOIN project_team pt USING (employee_id) WHERE pt.`project_code` IS NULL
INNER JOIN project p USING (project_code) WHERE (e.`employee_id` IS NULL)
答案 0 :(得分:0)
你可能想要这样的东西:
SELECT employee_id AS id_or_code, employee_name AS name_or_title FROM employee e LEFT JOIN project_team pt ON e.employee_id = pt.employee_id WHERE pt.project_code is NULL
UNION ALL
SELECT project_code AS id_or_code, project_title AS name_or_title FROM project p LEFT JOIN project_team pt ON p.project_code = pt.project_code WHERE pt.employee_id is NULL;
这样,您可以将查询结果分为两列,第一列作为员工或代码或项目的ID,第二列作为员工的名称或项目的标题。
答案 1 :(得分:0)
你需要全部加入,但MySQL没有。
在这里你可以找到联合解决方案https://stackoverflow.com/a/4796911/3970250
答案 2 :(得分:0)
您正在尝试将2个不同的选择记录合并到一个结果集中,一种方法是使用union all,然后将每个记录类型标记为
select
e.employee_id as id ,
e.employee_name as name,
'Employee' as type
from employee e
left join project_team pt on pt.employee_id = e.employee_id
where pt.employee_id is null
union all
select
p.project_code as id ,
p.project_title as name,
'Project' as type
from project p
left join project_team pt on pt.project_code = p.project_code
where pt.project_code is null ;
这是一个测试用例
mysql> select * from employee ;
+-------------+---------------+
| employee_id | employee_name |
+-------------+---------------+
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
| 5 | E |
+-------------+---------------+
5 rows in set (0.00 sec)
mysql> select * from project ;
+--------------+---------------+
| project_code | project_title |
+--------------+---------------+
| 1 | P1 |
| 2 | P2 |
| 3 | P3 |
| 4 | P4 |
+--------------+---------------+
4 rows in set (0.00 sec)
mysql> select * from project_team ;
+--------------+--------------+
| project_code | employee_id |
+--------------+--------------+
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 4 |
| 3 | 2 |
| 3 | 1 |
| 3 | 3 |
+--------------+--------------+
运行上述查询将为您提供
+------+------+----------+
| id | name | type |
+------+------+----------+
| 5 | E | Employee |
| 4 | P4 | Project |
+------+------+----------+