Column 'user_id' in field list is ambiguous

前端 未结 5 1470
醉梦人生
醉梦人生 2020-12-15 22:05

I am attempting to get the user information of the user who left this review.

With the following code:

SELECT username, image, user_id FROM table_use         


        
相关标签:
5条回答
  • 2020-12-15 22:26

    This is because user_id field exists in both tables. You need to specify which table's user_id you want.

    SELECT username, image, re.user_id
    
    0 讨论(0)
  • 2020-12-15 22:27

    Not only selected values(SELECT username, image, user_id) are examined in where clause (WHERE us.user_id = 1), all joined columns are examined in where clause, so in your example you have user_id column in both joined tables. If you have query like this one:

    SELECT table_reviews.id FROM table_users AS us
    JOIN table_reviews AS re
    ON re.user_id = us.user_id
    WHERE id
    

    id will be ambiguous because id-s from table_reviews and table_reviews will be examined in where clause although only id from table_reviews is selected.

    0 讨论(0)
  • 2020-12-15 22:33

    column user_id is in both table_reviews, table_users tables.

    You need to specify columns with table alias name also.

    SELECT username, image, us.user_id FROM table_users AS us
    JOIN table_reviews AS re
    ON re.user_id = us.user_id
    WHERE us.user_id = 1 AND
    re.review_id= 1
    
    0 讨论(0)
  • 2020-12-15 22:35

    It means column user_id is in both tables ie, in table_reviews, table_users

    Try like this:

    SELECT username, image, us.user_id    //or re.user_id
    FROM table_users AS us
    JOIN table_reviews AS re
    ON re.user_id = us.user_id
    WHERE us.user_id = 1 AND
    re.review_id= 1
    
    0 讨论(0)
  • 2020-12-15 22:36

    It means that both tables in the query have the column user_id.

    You need to specify which one you want to get in the SELECT statement like SELECT username, image, re.user_id

    0 讨论(0)
提交回复
热议问题