数据库位于:http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all。特别是我想获得1996年7月从Speedy Express Shipping Company订购产品订单并由员工服务的客户名单:Davolio Nancy和Peacock Margaret。结果应该是:
这是我的问题:
SELECT
c.CustomerName,
c.ContactName,
c.Address,
c.City,
c.PostalCode,
c.Country,
o.OrderDetailID,
s.Phone,
r.ProductName,
r.Price,
o.Quantity,
g.CategoryName
FROM Customers c
JOIN Orders d
on (c.CustomerID = d.CustomerID)
LEFT JOIN OrderDetails o
on (o.OrderID = d.OrderID)
LEFT JOIN Shippers s
on (s.ShipperID = d.ShipperID)
LEFT JOIN Products r
on (r.ProductID = o.ProductID)
LEFT JOIN Categories g
on (g.CategoryID = r.CategoryID)
LEFT JOIN Employees e
on (e.EmployeeID = d.EmployeeID)
WHERE s.ShipperName = 'Speedy Express' AND
((e.LastName = 'Davolio' AND e.FirstName = 'Nancy') OR
(e.lastName = 'Peacock' AND e.firstName = 'Margaret')) AND
EXTRACT(YEAR_MONTH FROM d.OrderDate) = 199607;
我收到的错误是:
ERROR 1: Could not prepare statement (1 near "FROM": syntax error)
当我删除最后一个条件(提取日期)时,如下所示:
SELECT c.CustomerName, c.ContactName, c.Address, c.City, c.PostalCode, c.Country, o.OrderDetailID, s.Phone, r.ProductName, r.Price, o.Quantity, g.CategoryName FROM Customers c JOIN Orders d on (c.CustomerID = d.CustomerID) LEFT JOIN OrderDetails o on (o.OrderID = d.OrderID) LEFT JOIN Shippers s on (s.ShipperID = d.ShipperID) LEFT JOIN Products r on (r.ProductID = o.ProductID) LEFT JOIN Categories g on (g.CategoryID = r.CategoryID) LEFT JOIN Employees e on (e.EmployeeID = d.EmployeeID) WHERE s.ShipperName = 'Speedy Express' AND((e.LastName = 'Davolio' AND e.FirstName = 'Nancy') OR (e.lastName = 'Peacock' AND e.firstName = 'Margaret'));
错误消失。那么请问我如何修复year_month条件而不会出错!
答案 0 :(得分:1)
这里的一种可能性是,无论出于何种原因,您的MySQL版本都不支持YEAR_MONTH
与EXTRACT()
一起使用。这里的一个解决方法是使用DATE_FORMAT()
代替:
WHERE DATE_FORMAT(d.OrderDate, '%Y%m') = '199607'
要测试您是否拥有旧版EXTRACT()
,请尝试运行以下简单查询:
SELECT EXTRACT(YEAR_MONTH FROM NOW());
如果出错,那么我的推测是正确的。