douyicao2199 2018-07-16 12:49
浏览 23
已采纳

mysql只拉取用户没有的行

My user group system has a table with these fields: user_id - group_id

So a user can have multiple groups, one for each row.

What I want to do, is pull records where they have a group_id of say "6" but not where they also have a group_id row where the value is "9".

I tried this:

SELECT u.`username` FROM `users` u INNER JOIN `user_group_membership` g ON u.user_id = g.user_id WHERE g.group_id != 9 AND g.group_id = 6 ORDER BY u.`username` ASC

However, that doesn't work, it still pulls in users who have a group_id that = 9.

  • 写回答

1条回答 默认 最新

  • 普通网友 2018-07-16 13:04
    关注

    As I understand you need to retrieve users in group 6 but not in group 9

    so you can try this solution

    SELECT u.`username` 
    FROM `users` u 
    INNER JOIN `user_group_membership` g6 ON u.user_id = g6.user_id and g6.group_id = 6 
    LEFT  JOIN `user_group_membership` g9 ON u.user_id = g9.user_id and g9.group_id = 9 
    WHERE g9.group_id is null
    ORDER BY u.`username` ASC
    

    you have issue in your sql because this condition will return all users in group 6 regardless if he is in group 9 or no

    g.group_id != 9 AND g.group_id = 6
    

    you need to edit your question to be more clear

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?