Overcoming ambiguous field error in SQL query

后端 未结 3 1946
野趣味
野趣味 2021-01-22 22:37

I have 4 tables and this query

SELECT tag.id, title
FROM tag
LEFT JOIN tag_map ON ( tag.id = tag_map.tag_id ) 
LEFT JOIN post ON ( post.id = post_id ) 
LEFT JOIN         


        
3条回答
  •  不要未来只要你来
    2021-01-22 23:19

    Based on the additional information supplied in a comment to another response, it appears that the a DIFFERENT title field needs to be selected depending on the post_type, with post_types corresponding to the post, game, and video tables.

    I'll assume that post_type is a one character text column.

    You can do that in two ways, with LEFT JOIN or UNION.

    SELECT tag.id, 
    CASE post_type 
       WHEN 'P' THEN post.title 
       WHEN 'V' THEN video.title 
       WHEN 'G' THEN game.title
    END CASE
    FROM tag
    LEFT JOIN tag_map ON ( tag.id = tag_map.tag_id ) 
    LEFT JOIN post ON ( post.id = post_id ) 
    LEFT JOIN game ON ( game.id = post_id ) 
    LEFT JOIN video ON ( video.id = post_id ) 
    WHERE tag_slug =  "blizzard"
    ORDER BY tag_map.post_type
    

    However, a UNION solution might be clearer:

    SELECT tag.id, post_type, title 
      FROM tag_map INNER JOIN post ON tag_map.post_id = post.id
    UNION ALL
    SELECT tag.id, post_type, title 
      FROM tag_map INNER JOIN game ON tag_map.post_id = game.id
    UNION ALL
    SELECT tag.id, post_type, title 
      FROM tag_map INNER JOIN video ON tag_map.post_id = video.id
    WHERE tag_slug =  "blizzard"
    ORDER BY tag_map.post_type
    

    (Note, I simplified the answers slightly because it's not clear to me the relation between tag and tag_map, you might need to introduce both tables into the SELECTS).

提交回复
热议问题