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

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

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan