我正在练习恢复MySQL的标准,并且使用Northlight练习数据库遇到了一个问题。我专门用这个网站进行练习:http://www.w3schools.com/sql/trysql.asp
我注意到员工Adam West(员工ID 10)在Orders表中没有出现任何事件。我正在尝试获取一个返回以下内容的列表:
FirstName LastName Number of Sales
Nancy Davolio 29
Andrew Fuller 20
Janet Leverling 31
Margaret Peacock 40
Steven Buchanan 11
Michael Suyama 18
Robert King 14
Laura Callahan 27
Anne Dodsworth 6
Adam West 0
但是,每次,底行(Adam West = 0)都不会返回。
我尝试了以下内容:
SELECT Employees.FirstName, Employees.LastName, COUNT(Employees.EmployeeID) as "Number of Sales"
FROM Employees
WHERE Employees.EmployeeID = Orders.EmployeeID
GROUP BY Orders.EmployeeID
我也尝试在LEFT JOIN Orders
行和FROM
行之间插入WHERE
,但无济于事。
答案 0 :(得分:1)
使用ON
时,您需要将该子句添加到LEFT JOIN
语句中。另外,由于Orders.EmployeeID
可能不存在,您需要GROUP BY Employees.EmployeeID
。
试试这个:
SELECT Employees.FirstName, Employees.LastName, COUNT(Orders.EmployeeID) as "Number of Sales"
FROM Employees
LEFT JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID
GROUP BY Employees.EmployeeID
答案 1 :(得分:0)
请从以下示例中了解:
CREATE TABLE Employees
(
EmployeeID INT,
FirstName VARCHAR(30),
LastName VARCHAR(30)
);
CREATE TABLE Orders
(
orderId INT,
EmployeeID INT
);
/ *表员工的数据* /
INSERT INTO employees(EmployeeID,FirstName,LastName) VALUES (1,'a','z');
INSERT INTO employees(EmployeeID,FirstName,LastName) VALUES (2,'b','y');
INSERT INTO employees(EmployeeID,FirstName,LastName) VALUES (3,'c','x');
/ *表格订单数据* /
INSERT INTO orders(orderId,EmployeeID) VALUES (101,1);
INSERT INTO orders(orderId,EmployeeID) VALUES (102,2);
INSERT INTO orders(orderId,EmployeeID) VALUES (103,1);
INSERT INTO orders(orderId,EmployeeID) VALUES (104,1);
SELECT Employees.FirstName, Employees.LastName, COUNT(orders.EmployeeID) AS "Number of Sales"
FROM Employees LEFT JOIN Orders
ON(Employees.EmployeeID = Orders.EmployeeID)
GROUP BY Orders.EmployeeID;
FirstName LastName Number of Sales
c X 0
a z 3
b Y 1
此处使用左连接。它将从左表中获取所有行,从右表中获取匹配的条目。这里没有订单表中的条目。
答案 2 :(得分:0)
我有同样的问题。这是我的解决方法...
蝙蝠侠卖给名字以辅音结尾的客户有多少订单?
SELECT em.EmployeeID, em.LastName, em.FirstName, COUNT(Customers.CustomerID) as 'number of orders'
FROM (SELECT *
FROM Employees
LEFT JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID
WHERE Employees.EmployeeID = 10) as em
LEFT JOIN Customers ON em.CustomerID = Customers.CustomerID
WHERE Customers.CustomerID is null
OR (Customers.CustomerName not LIKE '%a'
AND Customers.CustomerName not LIKE '%e'
AND Customers.CustomerName not LIKE '%i'
AND Customers.CustomerName not LIKE '%o'
AND Customers.CustomerName not LIKE '%u'
AND Customers.CustomerName not LIKE '%y')
结果:
EmployeeID LastName FirstName订单数
10西亚当0