简体   繁体   中英

Mysql Join tables with condition

I would like to list post and comments of a given user but also list the post where the given user did not comment yet.

Let's say I have the following tables & contents

Table Post

ID  TITLE
1   My post A
2   My post B
3   My post C

Table Comment

ID  COMMENT         POST_ID     USER_ID
1   My comment X        1          1
2   My comment Y        2          1
3   My comment Z        1          2

I run

select * from post 
left join comment on post.id = comment.post_id
where comment.user_id=1

and of course I got

ID  TITLE        ID    COMMENT          POST_ID    USER_ID
1   My post A     1    My comment X      1          1
2   My post B     2    My comment Y      2          1

I would like to get all posts event the one not commented by user 1 but I don't want the comment of user 2

ID  TITLE        ID    COMMENT          POST_ID    USER_ID
1   My post A     1    My comment X      1          1
2   My post B     2    My comment Y      2          1
3   My post C   

Thank you in advance for your help

Move your condition from where to on clause so you will get the posts even if user has not commented yet

select * from post 
left join comment
on post.id = comment.post_id
AND comment.user_id=1

See Demo Here

try this

select post.`ID`,`TITLE`,ifnull(`COMMENT`,0) comment,ifnull(`POST_ID`,0) `POST_ID`,
       ifnull(`USER_ID`,0) `USER_ID` 
from post 
left join comment
on post.id = comment.post_id
AND comment.user_id=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM