dongsi4547 2016-04-29 07: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 08: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条)

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?