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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?