neo*_*con 16 mysql sql join mysql-error-1066
这是我的表结构:
alt text http://img6.imageshack.us/img6/8730/articlek.jpg
错误消息是:
#1066 - 不是唯一的表/别名:'user'
以下是我的代码.
SELECT article.* , section.title, category.title, user.name, user.name
FROM article
INNER JOIN section ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user ON article.author_id = user.id
LEFT JOIN user ON article.modified_by = user.id
WHERE article.id = '1'
Run Code Online (Sandbox Code Playgroud)
cod*_*ike 34
您需要在第二次加入时为用户表提供别名
例如
SELECT article . * , section.title, category.title, user.name, u2.name
FROM article
INNER JOIN section ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user ON article.author_id = user.id
LEFT JOIN user u2 ON article.modified_by = u2.id
WHERE article.id = '1'
Run Code Online (Sandbox Code Playgroud)
你的错误是因为你有:
JOIN user ON article.author_id = user.id
LEFT JOIN user ON article.modified_by = user.id
Run Code Online (Sandbox Code Playgroud)
您有两个同一个表的实例,但数据库无法确定哪个是哪个.要解决此问题,您需要使用表别名:
JOIN USER u ON article.author_id = u.id
LEFT JOIN USER u2 ON article.modified_by = u2.id
Run Code Online (Sandbox Code Playgroud)
除非您喜欢在没有这些情况的情况下始终编写完整的表名,否则总是为您的表添加别名是一个好习惯.
接下来要解决的问题是:
SELECT article.* , section.title, category.title, user.name, user.name
Run Code Online (Sandbox Code Playgroud)
1)永远不要使用SELECT *- 总是拼出你想要的列,即使它是整个表. 阅读此SO问题以了解原因.
2)您将获得与列相关的模糊列错误,user.name因为数据库无法确定从哪个表实例提取数据.使用表别名可以解决问题:
SELECT article.* , section.title, category.title, u.name, u2.name
Run Code Online (Sandbox Code Playgroud)
您在FROM子句中两次提到"user".您必须提供至少一个提及的表别名,以便每次提及用户.可以固定到一个或另一个实例:
FROM article INNER JOIN section
ON article.section_id = section.id
INNER JOIN category ON article.category_id = category.id
INNER JOIN user **AS user1** ON article.author\_id = **user1**.id
LEFT JOIN user **AS user2** ON article.modified\_by = **user2**.id
WHERE article.id = '1'
Run Code Online (Sandbox Code Playgroud)
(你可能需要不同的东西 - 我猜测哪个用户是哪个,但SQL引擎不会猜测.)
此外,也许你只需要一个"用户".谁知道?