假设我有两张桌子:
如果我想列出属于位置1,2,或 3的员工,我会写一个类似于以下内容的查询:
SELECT DISTINCT e.id, e.name
FROM Employee e
JOIN EmpLocXref x ON x.employee_id = e.id
WHERE x.location_id IN (1, 2, 3)
;
但是,如果我想列出仅属于位置1,2,和 3的员工,该怎么办?我意识到我可以写一些类似的东西:
SELECT e.id, e.name
FROM Employee e
JOIN EmpLocXref x ON x.employee_id = e.id
WHERE x.location_id IN (1, 2, 3)
GROUP BY e.id, e.name
HAVING COUNT(*) = 3
;
有没有更好的方法可以做到这一点,不包括动态SQL?
编辑:修复了第二次查询时的derp时刻。添加了Fiddler示例。
答案 0 :(得分:3)
上面实际上不起作用,因为你永远不会在EmpLocXref中有一个记录,其中location_id是1和2和3同时。你得到零结果。试试这个:
SELECT DISTINCT e.*
FROM Employee e
INNER JOIN EmpLocXref x1 ON e.ID = x1.EmployeeID AND x1.Location_id = 1
INNER JOIN EmpLocXref x2 ON e.ID = x2.EmployeeID AND x2.Location_id = 2
INNER JOIN EmpLocXref x3 ON e.ID = x3.EmployeeID AND x3.Location_id = 3