我想查询w3school数据库

时间:2017-07-02 09:27:29

标签: mysql

数据库位于:http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all。特别是我想获得1996年7月从Speedy Express Shipping Company订购产品订单并由员工服务的客户名单:Davolio Nancy和Peacock Margaret。结果应该是:

  • 客户姓名,联系方式,地址,城市,邮政编码和国家/地区
  • 他们放置的orderDetailID
  • 运输公司的联系方式
  • 产品名称,价格和数量
  • 产品名称,价格和购买的单位
  • 产品类别

这是我的问题:

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条件而不会出错!

1 个答案:

答案 0 :(得分:1)

这里的一种可能性是,无论出于何种原因,您的MySQL版本都不支持YEAR_MONTHEXTRACT()一起使用。这里的一个解决方法是使用DATE_FORMAT()代替:

WHERE DATE_FORMAT(d.OrderDate, '%Y%m') = '199607'

要测试您是否拥有旧版EXTRACT(),请尝试运行以下简单查询:

SELECT EXTRACT(YEAR_MONTH FROM NOW());

如果出错,那么我的推测是正确的。