我想将两个表连接在一起,即运行表和餐厅表。从运行表中,我需要 run_id 和restaurant_id,从餐厅表中,我需要created_date,所以最后,我有一个包含每个餐厅的created_date 的表。 run 和 Restaurant_history 表都有 run_id,因此我知道我可以加入它们。我想出了类似的东西:
SELECT run_id, restaurant_id, created_date FROM restaurant_history, run
JOIN run ON restaurant_history.run_id = run.run_id;
但这给了我一个错误。任何帮助将不胜感激:)
(我对 sql 还很陌生)
最佳答案
您正在混合隐式连接和显式连接。隐式联接语法(列出 FROM
子句中的表)已被弃用 over 25 years ago .
作为一个简单的规则,切勿在 FROM
子句中使用逗号:
SELECT R.run_id, restaurant_id, created_date
FROM restaurant_history H
JOIN run R ON H.run_id = R.run_id;
至于为什么它给你这个错误,错误有两个方面。让我们看看您写的内容:
SELECT run_id, restaurant_id, created_date
FROM restaurant_history, run
JOIN run ON restaurant_history.run_id = run.run_id;
您之前的查询相当于以下内容:
SELECT run_id, restaurant_id, created_date
FROM restaurant_history
CROSS JOIN run
INNER JOIN run ON restaurant_history.run_id = run.run_id;
错误的原因是您的表 run
在查询中列出了两次,而没有别名来区分这两个表。 ON
子句引用了 run
表,但它不知道您指的是哪一个。
此外,您无意中在 restaurant_history
和 run
之间创建了 CROSS JOIN
- 我确信您不希望这样做。
但是,仅从 FROM
子句中删除第二个表仍然会给您带来有关 SELECT
中不明确列 (run_id
) 的错误陈述。该列存在于两个表中(正如我们从JOIN
中看到的),如果没有明确告诉它从哪个表中选择,它不知道如何处理该列,并且会抛出错误。
要解决此问题,您还需要为表添加别名(我在解决方案中放入的 H
和 R
别名)。
有关不同 JOIN
类型的更多信息,请参阅此问题:
What is the difference between "INNER JOIN" and "OUTER JOIN"?
有关显式与隐式 JOIN
的更多信息,请参阅此处:
Bad habits to kick : using old-style JOINs
关于mysql - 学习如何连接表,但收到错误消息 "Not unique table",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42397114/