2017-05-28 115 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' –