2011-08-02 85 views
2

我已經存儲了用戶的帖子在表中調用領域帖子與條件添加一個額外的列在聯合查詢

id 
userid 
posttitle 
status 

我已經存儲了用戶收藏的帖子在fav_posts表的字段

id 
post_id 
userid 

帖子表

代碼:

id userid  posttitle status 
1 1200 title 1 Active 
2 1200 title 2 Active 
3 1200 title 3 Active 
4 1200 title 4 Active 
5 1201 title 5 Active 
6 1201 title 6 Active 
7 1201 title 7 Active 
8 1201 title 8 Active 

Fav_posts表 代碼:

id post_id  userid 
1 1 1200 
2 2 1201 
3 5 1202 
4 6 1202 
5 6 1201 
6 8 1201 
7 8 1200 
8 7 1200 

現在 如果我輸入的用戶 我得的是存在於兩個表 的記錄,但應該只來過一次 並設有獨立的字段值 即 如果我進入ID爲1200 結果應該是

代碼:

post_id  title post_came_in 
1 title 1 BOTH 
8 title 8 FAV 
7 title 7 FAV 
2 title 2 MYPOST 
3 title 3 MYPOST 
4 title 4 MYPOST 

我能夠列出聯盟榜首 但我不知道如何納入結果檢查後成立的第三個字段,發現相同的記錄來在我的職位和崗位最愛

我同時使用下面的查詢來獲取聯盟結果

SELECT post_id,title 
FROM posts 
LEFT JOIN fav_posts ON posts.id = fav_posts.post_id WHERE fav_posts.userid = 1200 
UNION ALL 
SELECT id AS post_id,title FROM posts WHERE userid = 1200 

請告訴我,我怎麼能在查詢

問候一個檢查標準 ANEES

回答

0
SELECT post_id, title, 'FAV' AS `post_came_in` FROM posts LEFT JOIN fav_posts ON posts.id = fav_posts.post_id WHERE fav_posts.userid = 1200 
UNION ALL 
SELECT id AS post_id, title, 'MYPOST' AS `post_came_in` FROM posts WHERE userid = 1200 
2
SELECT 
post_id, title, 
CASE WHEN posts.id IS NULL THEN 'FAV' 
     WHEN fav_posts.id IS NULL AND posts.id IS NOT NULL THEN 'MYPOST' 
     ELSE 'BOTH' 
END post_came_in 
FROM 
posts FULL JOIN fav_posts ON posts.id = fav_posts.post_id 
WHERE 
(fav_posts.userid = 1200) OR (posts.userid = 1200)