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 game ON ( game.id = post_id )
LEFT JOIN video ON ( video.id = post_id )
WHERE tag_slug = "blizzard"
ORDER BY tag_map.post_type
The problem in this query is that the 3 tables on the left join statement all have a title column. Because of this I'm getting the "Column 'title' in field list is ambiguous" error.
How can I handle this so that the query shows the related title field for each row..
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
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).
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
精彩评论