我有3张桌子 1:员工 2:部门 3:专家
我想要属于CmpId = 1的专家
员工:
id CmpId
1 2
2 1
3 1
部门
id CmpId
1 1
2 2
3 2
专家:
id EmployeeId DepartmentId
1 1 2
2 2 null
3 null 1
4 2 1
5 null null
答案 0 :(得分:1)
INNER加入三个表
如果它们需要在BOTH中为CmpId = 1(这样在样本数据中不返回任何内容,但假设它是一个更大的数据集)
SELECT e.id, e.EmployeeId, e.DepartmentId
FROM Experts e
FULL OUTER JOIN Department d ON e.DepartmentId = d.id
FULL OUTER JOIN Employee em ON e.EmployeeId = em.id
WHERE d.CmpId = 1 AND em.CmpId = 1
如果他们需要在Cither中为CmpId = 1
SELECT e.id, e.EmployeeId, e.DepartmentId
FROM Experts e
FULL OUTER JOIN Department d ON e.DepartmentId = d.id
FULL OUTER JOIN Employee em ON e.EmployeeId = em.id
WHERE d.CmpId = 1 OR em.CmpId = 1
答案 1 :(得分:1)
让我猜一下NULL
表中的expert
表示某人是所有部门的专家。如果是这样的话:
select e.employeeid
from experts e join
departments d
on e.departmentid = d.id or e.departmentid is null;
答案 2 :(得分:1)
如果我正确理解了这个问题,那么基于样本数据的预期结果应该是专家ID的2,3和4。
专家ID 2的员工ID为2,其CmpID为1。 专家ID 3的部门ID为1,其CmpID为1。 专家ID 4的员工ID为2,其CmpID为1,部门ID为1,CmpID为1。
如果这实际上是所需的结果集,我会写下面的查询。
SELECT ex.id, ex.EmployeeID, ex.DepartmentID
FROM @Experts ex
LEFT JOIN @Department dep
ON ex.DepartmentID = dep.id
LEFT JOIN @Employee emp
ON ex.EmployeeID = emp.id
WHERE dep.CmpID = 1 OR emp.CmpID = 1
这将产生以下结果。
id EmployeeID DepartmentID
2 2 NULL
3 NULL 1
4 2 1