简体   繁体   English

1052:在以下情况下,字段列表中的列“ user_id”不明确

[英]1052: Column 'user_id' in field list is ambiguous when

I have 3 tables which share a user id, now I want to get data from all 3 but I don't know where I'm doing it wrong in this query 我有3个共享用户ID的表,现在我想从所有3个表中获取数据,但是我不知道在此查询中我在哪里做错了

SELECT user_id, first_name, image_id, description, gender 
FROM users a 
JOIN user_services b ON b.user_id = a.user_id 
JOIN user_timeframe c ON c.user_id = a.user_id

Two key best practices: 两个关键的最佳实践:

  • Always qualify all column references. 始终限定所有列引用。
  • Use table aliases that are meaningful rather than arbitrary letters. 使用有意义的表别名,而不是任意字母。

So: 所以:

SELECT u.user_id, u.first_name, ?.image_id, ?.description, 
       u.gender 
FROM users u JOIN
     user_services us
     ON us.user_id = u.user_id JOIN
     user_timeframe ut
     ON ut.user_id = u.user_id;

The ? ? is because it is not clear what table those columns come from. 因为不清楚这些列来自哪个表。 (The other columns are guesses so they might not be right either.) (其他专栏都是猜测,因此它们可能也不正确。)

The preferred way should be explicit aliasing. 首选方式应该是显式别名。 There is another way to fix this query by using JOIN ... USING syntax: 还有一种使用JOIN ... USING语法来修复此查询的方法:

SELECT user_id, first_name, image_id, description, gender 
FROM users a 
JOIN user_services b USING(user_id)
JOIN user_timeframe c USING(user_id);

db<>fiddle demo db <> fiddle演示

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

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