在Union Query中添加带条件的额外列

时间:2011-08-02 18:30:29

标签: mysql

我已将用户帖子存储在名为posts with fields

的表中
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

现在 如果我输入一个用户 我必须得到两个表中都存在的记录 但应该只来一次 并具有单独的Field值 即 如果我输入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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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