为什么此 SQL 代码会给出错误 1066(不是唯一的表/别名:“用户”)?
这是我的表结构:
错误信息是:
#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'
This is my table structure:
The error message is:
#1066 - Not unique table/alias: 'user'
The following is my code.
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的错误是因为您有:
您有同一个表的两个实例,但数据库无法确定哪个是哪个。要解决此问题,您需要使用表别名:
始终为表添加别名是一个好习惯,除非您喜欢在没有此类情况时始终编写完整的表名称。
接下来要解决的问题是:
1) 切勿使用
SELECT *
- 始终拼写出所需的列,即使它是整个表。 阅读这个问题以了解为什么。2) 您将收到与
user.name
列相关的不明确的列错误,因为数据库无法判断从哪个表实例中提取数据。使用表别名可以解决此问题:Your error is because you have:
You have two instances of the same table, but the database can't determine which is which. To fix this, you need to use table aliases:
It's good habit to always alias your tables, unless you like writing the full table name all the time when you don't have situations like these.
The next issues to address will be:
1) Never use
SELECT *
- always spell out the columns you want, even if it is the entire table. Read this SO Question to understand why.2) You'll get ambiguous column errors relating to the
user.name
columns because again, the database can't tell which table instance to pull data from. Using table aliases fixes the issue:您在 FROM 子句中两次提到“用户”。您必须为至少一个提及项提供表别名,以便每次提及用户。可以固定到一个或另一个实例:(
您可能需要不同的东西 - 我猜测哪个用户是哪个,但 SQL 引擎不会猜测。)
此外,也许您只需要一个“用户”。谁知道?
You have mentioned "user" twice in your FROM clause. You must provide a table alias to at least one mention so each mention of user. can be pinned to one or the other instance:
(You may need something different - I guessed which user is which, but the SQL engine won't guess.)
Also, maybe you only needed one "user". Who knows?
希望这可能有帮助
Hope This Might Help
您需要在第二次加入用户表时为其指定一个别名
,例如
You need to give the user table an alias the second time you join to it
e.g.