什么是连接语句中AND和WHERE之间的区别

时间:2017-08-21 18:02:42

标签: sql

当我执行一些SQL命令时,我不知道为什么结果会发生变化,所以我一直坐在W3学校并且搔痒我的大脑。

所以这是W3学校的例子:

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
where LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

输出结果为:Davolio 29

所以我的问题是,当我将代码更改为

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
and LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

输出结果为:Davolio 29 Fuller 196

这里发生了什么,我还没有找到一个正确的解释,为什么只有196个订单的富勒才会将它改为AND,为什么会有差异呢?

1 个答案:

答案 0 :(得分:2)

第二种情况的逻辑是:

ON (Orders.EmployeeID = Employees.EmployeeID and LastName = 'Davolio') OR
   (LastName = 'Fuller')

您可以使用括号获得相同的结果:

ON Orders.EmployeeID = Employees.EmployeeID and
   (LastName = 'Davolio' OR LastName = 'Fuller')

或更简单地使用IN

ON Orders.EmployeeID = Employees.EmployeeID and
   LastName IN ('Davolio', 'Fuller')