mySQL内部连接多个表

时间:2016-10-31 18:13:24

标签: mysql phpmyadmin inner-join

如果我发布这行代码:

SELECT Cheese.Chesse_Name
FROM Customer
INNER JOIN Customer ON Customer.Customer_ID = Orders.Customer_ID
INNER JOIN Orders ON Orders.Orders_ID = OrderSandwich.Orders_ID
INNER JOIN OrderSandwich ON OrderSandwich.Sandwich_ID = Sandwich.Sandwich_ID
INNER JOIN Sandwich ON Sandwich.Cheese_ID = Cheese.Cheese_ID
WHERE Customer.CustomerID = 1;

我从DB获得的是一个错误

Fehler

SQL-Befehl: Dokumentation

SELECT Cheese.Chesse_Name
FROM Customer
INNER JOIN Customer ON Customer.Customer_ID = Orders.Customer_ID
INNER JOIN Orders ON Orders.Orders_ID = OrderSandwich.Orders_ID
INNER JOIN OrderSandwich ON OrderSandwich.Sandwich_ID = Sandwich.Sandwich_ID
INNER JOIN Sandwich ON Sandwich.Cheese_ID = Cheese.Cheese_ID
WHERE Customer.CustomerID = 1
 LIMIT 0, 25 

MySQL meldet: Dokumentation
#1066 - Not unique table/alias: 'Customer' 

我现在正在尝试这几个小时,不要说这一天。

这是数据库图表:

enter image description here

如果有人马上看到我犯的错误

,我会非常感激

3 个答案:

答案 0 :(得分:3)

您正试图加入Customer表格。重新组织您的JOIN查询,如下所示。

SELECT Cheese.Cheese_Name
FROM Customer
INNER JOIN Orders ON Customer.Customer_ID = Orders.Customer_ID
INNER JOIN OrderSandwich ON Orders.Orders_ID = OrderSandwich.Orders_ID
INNER JOIN Sandwich ON OrderSandwich.Sandwich_ID = Sandwich.Sandwich_ID
INNER JOIN Cheese ON Sandwich.Cheese_ID = Cheese.Cheese_ID
WHERE Customer.Customer_ID = 1;

请记住,您正在调用JOIN语句,将上述表格加入上表。例如,如果你打电话

Customer
INNER JOIN Orders ON Customer.Customer_ID = Orders.Customer_ID

您正在使用Customer表加入Orders表。无需两次提及Customer表。

答案 1 :(得分:1)

试试这个:

SELECT Cheese.Chesse_Name
FROM Customer
INNER JOIN Orders ON Customer.Customer_ID = Orders.Customer_ID
INNER JOIN OrderSandwich ON Orders.Orders_ID = OrderSandwich.Order_ID
INNER JOIN Sandwich ON OrderSandwich.Sandwich_ID = Sandwich.Sandwich_ID
INNER JOIN Cheese ON Sandwich.Cheese_ID = Cheese.Cheese_ID
WHERE Customer.CustomerID = 1;

答案 2 :(得分:1)

在我看来,你需要将所有内连接表向上移动一个并将最后一个更改为干酪。 (删除不需要/所需的第二次加入给客户)

SELECT Cheese.Chesse_Name
FROM Customer
INNER JOIN Orders ON Customer.Customer_ID = Orders.Customer_ID
INNER JOIN Ordersandwich ON Orders.Orders_ID = OrderSandwich.Orders_ID
INNER JOIN sandwich ON OrderSandwich.Sandwich_ID = Sandwich.Sandwich_ID
INNER JOIN cheese ON Sandwich.Cheese_ID = Cheese.Cheese_ID
WHERE Customer.CustomerID = 1;