donglizhan7848 2013-05-21 22:27
浏览 56
已采纳

MySQL多个WHERE子句到同一列

I have a table of users where all information is in a 1-to-1 relationship...

    users table

    ------------------------
    id        |   name
    ------------------------
    800       |  Bob Smith
    801       |  Jane Doe
    802       |  Fred Flintstone
    803       |  Barney Rubble
    804       |  Marge Simpson

I also have another many-to-1 relationship table which houses the usergroup mapping of all users to the group(s) that they are part of

    user_usergroup_map table

    ------------------------
    user_id   |   group_id
    ------------------------
    800       |  16
    800       |  27
    801       |  25
    801       |  27
    802       |  17
    802       |  19
    802       |  22
    802       |  25
    803       |  25
    803       |  27
    804       |  15

I am trying to generate an array of distinct users that are part of 2 distinct groups. At the same time, I am trying to keep this all within a single array (for which I will be using as a pagination reference).

I have been able to successfully query both tables via a JOIN statement...

    $group_id1 = 25;
    $group_id2 = 27;

    $query = SELECT DISTINCT name, id FROM users INNER JOIN user_usergroup_map on user_usergroup_map.user_id=users.id WHERE group_id IN('$group_id1', '$group_id2');

However, with this, I get a distinct list of users who are part of EITHER group_id 15 or group_id 27, instead of those who are part of both groups. I know that I've been staring at this for far too long, and I'm missing some simplistic logical element, but I just can't see it, for the life of me. If anyone out there could shed some light on what I'm probably doing wrong, I'd GREATLY appreciate it.

  • 写回答

4条回答 默认 最新

  • dpa89292 2013-05-22 00:53
    关注

    Assuming you have a constraint on user_usergroup_map table such that a given user cannot be assigned to the same group_id twice, you can do something like this:

    Select ...
    From users
    Where id In (
                Select user_id
                From user_usergroup_map
                Where group_id In(25,27)
                Group By user_id
                Having Count(*) = 2
                )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?