开发者

Add an extra column with condition in Union Query

开发者 https://www.devze.com 2023-03-25 07:14 出处:网络
i have stored user Posts in a table called posts with fields id userid posttitle status i have stored user favorited posts in fav_posts table with fields

i have stored user Posts in a table called posts with fields

id
userid
posttitle
status

i have stored user favorited posts in fav_posts table with fields

id
post_id
userid

Post table

Code:

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 table Code:

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

Now if i input an user i have to get the records that exists in both table but should come only once and with a separate Field value ie if i entered id as 1200 the result should be

Code:

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

i am able to list out the union list but i don't know how to include the third field in the result set after checking and found that the same record comes in both My posts and favorited posts

i used the below query to get the Union result

SELECT post_id,title 
FROM posts 
LEFT JOIN fav_posts ON posts.id = fav_posts.post_id WHERE fav_posts.userid = 1200
U开发者_开发问答NION ALL
SELECT id AS post_id,title FROM posts WHERE userid = 1200

Please tell me how could i include a checking criteria in the query

Regards Anees


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)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号