简体   繁体   English

user_id的列名错误

[英]Ambiguous column name error for user_id

My users table has the columns user_id , email My invites table has the columns invite_id request_id user_id sent_time 我的用户表具有列user_idemail我的邀请表具有列invite_id request_id user_id sent_time

When I run the following query, I get the two tables joined into 1, which is expected. 当我运行以下查询时,我将两个表合并为1,这是预期的。

'SELECT * FROM users INNER JOIN invites ON users.user_id = invites.user_id'

However, when I run the following query, 但是,当我运行以下查询时,

'SELECT user_id FROM users INNER JOIN invites ON users.user_id = invites.user_id'

I get the following error 我收到以下错误

OperationalError: (sqlite3.OperationalError) ambiguous column name: user_id [SQL: 'SELECT user_id FROM users INNER JOIN invites ON users.user_id = invites.user_id']

Any help appreciated. 任何帮助表示赞赏。

I think the message is pretty clear. 我认为信息很明确。 SQLite doesn't know what table user_id is coming from. SQLite不知道表user_id来自何处。

One simple solution is to qualify the column name usinga table alias: 一种简单的解决方案是使用表别名来限定列名:

SELECT u.user_id
FROM users u INNER JOIN
     invites i
     ON u.user_id = i.user_id;

Another method is to use USING rather than ON : 另一种方法是使用USING而不是ON

SELECT user_id
FROM users u INNER JOIN
     invites i
     USING (user_id);

You need to qualify the column name with table name like below cause both table involved in query have the same column name 您需要使用表名来限定列名,如下所示,因为参与查询的两个表都具有相同的列名

SELECT `users`.user_id 
FROM users 
INNER JOIN invites ON `users`.user_id = invites.user_id

This means you need to be specific about which user_id column you want to display. 这意味着你必须是具体哪些 user_id要显示的列。 Even though they're joined that doesn't guarantee they're identical. 即使他们加入,也不能保证他们是相同的。 Some types of joins allow NULL values on one side of the match (eg LEFT JOIN ), so you need to ask for a particular value: 某些类型的联接在匹配的一侧允许使用NULL值(例如LEFT JOIN ),因此您需要询问一个特定的值:

SELECT users.user_id FROM users INNER JOIN invites ON users.user_id = invites.user_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM