SelectClassicModels.Orders.CustomerNumber,
ClassicModels.CUSTOMERS.CUSTOMERNAME,
ClassicModels.Employees.LASTNAME,
ClassicModels.Employees.firstNAME,
ClassicModels.employees.EmployeeNumber
from ClassicModels.Orders
join
ClassicModels.Customers
on ClassicModels.Orders.CustomerNumber = ClassicModels.Customers.CUSTOMERNUMBER
join
ClassicModels.EMPLOYEES
on ClassicModels.Employees.EMPLOYEENUMBER = ClassicModels.CUSTOMERS.SalesRepEmployeeNumber
加入时这三张桌子工作得很好,但是当我尝试添加这些修改器时,他们不能正常工作
group by ClassicModels.Orders.CustomerNumber
having count(ClassicModels.Orders.CustomerNumber) < 4
答案 0 :(得分:1)
首先,欢迎来到StackOverflow!
我已经使用我最喜欢的工具重新格式化了您的SQL,如果您有兴趣我可以提供链接。我还添加了别名,以帮助使其更具可读性[#34; (别名是FROM
和JOIN
子句中表名后面的小写位。)
SELECT orders.CustomerNumber,
customers.CustomerName,
employees.LastName,
employees.FirstName,
employees.EmployeeNumber
FROM CLASSICMODELS.ORDERS orders
JOIN CLASSICMODELS.CUSTOMERS customers
ON orders.CustomerNumber = customers.CustomerNumber
JOIN CLASSICMODELS.EMPLOYEES employees
ON employees.EmployeeNumber = customers.SalesRepEmployeeNumber
现在我们已经完成了。让我们添加您的GROUP BY
和HAVING
条款。
GROUP BY
子句必须包含<{1}}子句中使用的 ALL 列。 (我不知道为什么。我还没看过,但我知道它是如何运作的。:))
SELECT
现在应该可行。然后你只需要在那里添加SELECT orders.CustomerNumber,
customers.CustomerName,
employees.LastName,
employees.FirstName,
employees.EmployeeNumber
FROM CLASSICMODELS.ORDERS orders
JOIN CLASSICMODELS.CUSTOMERS customers
ON orders.CustomerNumber = customers.CustomerNumber
JOIN CLASSICMODELS.EMPLOYEES employees
ON employees.EmployeeNumber = customers.SalesRepEmployeeNumber
GROUP BY orders.CustomerNumber,
customers.CustomerName,
employees.LastName,
employees.FirstName,
employees.EmployeeNumber
子句。
HAVING
我也在查看您的查询,并且可能通过使用如下查询获得更快(并且效率更高的结果):
SELECT orders.CustomerNumber,
customers.CustomerName,
employees.LastName,
employees.FirstName,
employees.EmployeeNumber
FROM CLASSICMODELS.ORDERS orders
JOIN CLASSICMODELS.CUSTOMERS customers
ON orders.CustomerNumber = customers.CustomerNumber
JOIN CLASSICMODELS.EMPLOYEES employees
ON employees.EmployeeNumber = customers.SalesRepEmployeeNumber
GROUP BY orders.CustomerNumber,
customers.CustomerName,
employees.LastName,
employees.FirstName,
employees.EmployeeNumber
HAVING COUNT(orders.CustomerNumber) < 4
它使用所谓的&#34;公用表表达式&#34;并且基本上只是隔离了一部分查询。它可能更有效率,因为它会尝试对较少的数据进行分组,因此可能会更快。要小心,因为那里有许多可能的东西,因为我不知道你的MySQL数据库中是如何设置各种不同的东西的。
祝你好运!