首先,歡迎StackOverflow的這三個表!
我已經使用我最喜歡的工具重新格式化了SQL,如果您有興趣,我可以提供一個鏈接。我還添加了別名以幫助使其更「易讀」。 (別名是在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
子句必須有所有的子句中使用的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
我也找過你的查詢,你可能通過使用這樣的查詢獲得更快(更有效的結果):
WITH CUSTOMERSWITHLESSTHANFOURORDERS
AS
(
SELECT CUSTOMERNUMBER
FROM CLASSICMODELS.ORDERS
GROUP BY CUSTOMERNUMBER
HAVING COUNT(CUSTOMERNUMBER) < 4
)
SELECT O.CUSTOMERNUMBER,
C.CUSTOMERNAME,
E.LASTNAME,
E.FIRSTNAME,
E.EMPLOYEENUMBER
FROM CUSTOMERSWITHLESSTHANFOURORDERS O
JOIN CLASSICMODELS.CUSTOMERS C
ON O.CUSTOMERNUMBER = C.CUSTOMERNUMBER
JOIN CLASSICMODELS.EMPLOYEES E
ON E.EMPLOYEENUMBER = C.SALESREPEMPLOYEENUMBER;
它採用的是所謂「通用表表達式「,基本上只隔離了一部分查詢。它可能會更有效率,因爲它會嘗試將更少的數據分組,所以它可能會更快。要小心,因爲裏面有很多「可能」,因爲我不知道你的MySQL數據庫中設置了多種不同的東西。
祝你好運!
你先生是個天才。我不知道所有人都有必要組隊。我不能夠感謝你 –