如何进行INNER JOIN查询?

时间:2017-05-28 18:13:57

标签: sql join 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 
;

我收到此错误:

  

您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以便在第16行的“FROM Customer AS c,DonutOrder AS o,OrderLineItem AS i,Donut AS d INN”附近使用正确的语法。

有什么问题?

以下是我的SQL小提琴页面的链接:http://sqlfiddle.com/#!9/a2842/7

1 个答案:

答案 0 :(得分: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