2017-07-02 43 views
1

該數據庫位於:http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all。特別是我希望獲得1996年7月從Speedy Express Shipping Company下達產品訂單的客戶名單,並由員工Davolio Nancy和Peacock Margaret提供服務。結果應該有:我要查詢w3school數據庫

  • 客戶,聯繫人,地址,城市,郵政編碼和國家
  • 的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條件而不會出現錯誤!

+0

您使用的是哪個版本的MySQL? –

+0

我在w3schools.com上使用sql編輯器 –

回答

1

這裏的一種可能性是,無論出於何種原因,您的MySQL版本都不支持YEAR_MONTHEXTRACT()一起使用。這裏的一個解決辦法是使用DATE_FORMAT()代替:

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

要測試你是否有一箇舊版本的EXTRACT(),只是嘗試運行下面的簡單查詢:

SELECT EXTRACT(YEAR_MONTH FROM NOW()); 

如果這樣的錯誤了,那麼我的猜想是正確的。