2017-05-28 78 views
-1

我有這個疑問:如何做一個INNER JOIN查詢?

SELECT o.Date, 
    CONCAT (c.FirstName, '', c.LastName), 
    c.StreetAddress, 
    c.Apt, 
    c.City, 
    c.State, 
    c.ZipCode, 
    c.HomePhone, 
    c.MobilePhone, 
    c.OtherPhone, 
    i.Quantity, 
    d.DonutName, 
    d.Description, 
    d.UnitPrice, 
    o.Notes, 
FROM Customer AS c, 
    DonutOrder AS o, 
    OrderLineItem AS i, 
    Donut AS d 
INNER JOIN DonutOrder AS o ON c.CustomerID = o.CustomerID 
INNER JOIN Donut AS d ON o.DonutOrderID = i.DonutOrderID 
INNER JOIN OrderLineItem AS i ON d.DonutID = i.DonutID 
; 

我收到此錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Customer AS c, DonutOrder AS o, OrderLineItem AS i, Donut AS d INN' at line 16.

有什麼不對?

這裏是鏈接到我的SQL小提琴頁:http://sqlfiddle.com/#!9/a2842/7

回答

1

你有幾個問題:

  • 的誤差大約在select列表後面的逗號:最後一個字段不應該跟着一個逗號
  • from子句不應該提到一個表,除非你打算如此。但是在這種情況下你只有想用inner join,而不是逗號分隔的列表。
  • 將參加最後兩個連接表的條件應該被移動到其他連接(交換)
  • 第一場在select列表不存在。您可能打算使用o.OrderDate
  • 在您的小提琴中,OrderLineItem表中沒有數據,因此即使已更正,您的查詢也不會返回任何行。

這裏是修正版本:

SELECT o.OrderDate, 
    CONCAT (c.FirstName, '', c.LastName), 
    c.StreetAddress, 
    c.Apt, 
    c.City, 
    c.State, 
    c.ZipCode, 
    c.HomePhone, 
    c.MobilePhone, 
    c.OtherPhone, 
    i.Quantity, 
    d.DonutName, 
    d.Description, 
    d.UnitPrice, 
    o.Notes 
FROM Customer AS c 
INNER JOIN DonutOrder AS o ON c.CustomerID = o.CustomerID 
INNER JOIN OrderLineItem AS i ON o.DonutOrderID = i.DonutOrderID 
INNER JOIN Donut AS d ON d.DonutID = i.DonutID 
; 

http://sqlfiddle.com/#!9/a2842/15

+0

是的,我確實意味着訂購日期!感謝您在我的選擇結束時注意到額外的逗號。我甚至沒有想到我的OrderLineItem表中沒有數據。那麼在查詢中沒有必要呢? –

+0

那麼,這取決於你在輸出中想要什麼。正如您現在所見,您需要'OrderLineItem'表中的數據,因爲您從中選擇數量。這完全取決於你想要輸出什麼,以防在那裏沒有數據。也許你想要執行一個外部連接......讓你來決定。 – trincot

+0

我刪除了OrderLineItem及其所有語句,然後在我的Select語句中添加了DonutID和DonutOrderID,現在我收到錯誤:'on子句'中的未知列'c.CustomerID' –