使用外连接的SQL查询?

时间:2016-03-03 21:21:10

标签: sql postgresql join left-join outer-join

我有以下关系:

enter image description here

我希望列出2014年6月之前加入公司但在2014年6月未使用某种外部联接收到佣金的所有员工。我想出了这个查询,但它没有用。有人能告诉我如何查询吗?

SELECT DISTINCT Employee.EmpId, Employee.EmpName
FROM Employee
LEFT OUTER JOIN Commission
ON Employee.EmpId = Commission.EmpId
WHERE Employee.JoinDate BETWEEN Employee.JoinDate AND '2014-06-31'
GROUP BY Employee.EmpId, Employee.EmpName
HAVING COUNT(Commission.Commdate BETWEEN '2014-06-01' AND '2014-06-31') = 0
ORDER BY Employee.EmpId

1 个答案:

答案 0 :(得分:1)

LEFT JOIN是一个好主意。但是,您希望佣金日期在ON子句中。然后找到不匹配的员工。所以,这是查询的一个版本(清理使用表别名):

SELECT e.EmpId, e.EmpName
FROM Employee e LEFT OUTER JOIN
     Commission c
     ON e.EmpId = c.EmpId AND
        c.Commdate BETWEEN '2014-06-01' AND '2014-06-31'
WHERE e.JoinDate < '2014-06-01' AND c.EmpID IS NULL
GROUP BY e.EmpId, e.EmpName
ORDER BY e.EmpId;

但是,编写查询的一种更自然的方法是:

SELECT e.*
FROM employee e
WHERE NOT EXISTS (SELECT 1
                  FROM Commission c
                  WHERE e.EmpId = c.EmpId AND
                        c.Commdate BETWEEN '2014-06-01' AND '2014-06-31'
                 ) AND
       e.JoinDate < '2014-06-01';