dongsi4547 2016-04-28 23:54
浏览 89
已采纳

如何获取用户id不在表记录mysql中的选定行

How get selected rows where user id is not in table record

the table like this

table_a

id subid userid
1  2     123
2  4     123

table_b

id title
1  like
2  liked
3  bookmark
4  bookmarked

i use join table to get the result if WHERE userid=123 then get result

id title
2  liked
4  bookmarked

the query

select b.id,b.title from
table_a a
LEFT JOIN table_b b
ON b.id = a.subid
WHERE a.userid = '123'

but, how if userid = '345' and not in table_a get the result too?.. the result is must like this (selected rows)

id title
1  like
3  bookmark

Thankyou

  • 写回答

4条回答 默认 最新

  • douya2433 2016-04-29 00:03
    关注

    You can use the following query:

    SELECT id, title FROM t2 LEFT JOIN t1 ON t1.subid = t2.id 
    WHERE (t1.userid = 345 AND NOT userid IS NULL) OR (
        NOT EXISTS(SELECT userid FROM t1 WHERE userid = 345) AND userid IS NULL
    );
    

    The working examples you can find here: http://sqlfiddle.com/#!9/c6a446/25

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部