Overcoming ambiguous field error in SQL query

后端 未结 3 1899
野趣味
野趣味 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条回答
  • 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).

    0 讨论(0)
  • 2021-01-22 23:22
    SELECT 
    tag.id, 
    tag_map.title as tagmaptitle,
    post.title as posttitle,
    game.title as gametitle,
    video.title as viedotitle,
    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
    
    0 讨论(0)
  • 2021-01-22 23:23

    You need to specify which table you want title to come from. Taking a guess that title will be in game you would need to specify game.title.

    If I were you I'd start looking into splitting this down a bit using temporary tables. Although theres nothing wrong with 4 joins it does tend to start getting confusing.

    Example temp table:

    CREATE TABLE #Yaks (
    YakID int,
    YakName char(30) )
    

    In your scenario you would create a temp table and then fill it with an INSERT and UPDATE based on individual joins so at the end all you have to do is SELECT * FROM @temptable

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