SQL 使用外连接查询?
SQL Query using outer join?
我有以下关系:
我想列出所有在 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
LEFT JOIN
是个好主意。但是,您需要 ON
子句中的佣金日期。然后找到不匹配的员工。所以,这是查询的一个版本(清理后使用 table 别名):
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';
我有以下关系:
我想列出所有在 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
LEFT JOIN
是个好主意。但是,您需要 ON
子句中的佣金日期。然后找到不匹配的员工。所以,这是查询的一个版本(清理后使用 table 别名):
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';