4

我有一张这样的桌子:

---------------------
| id | user | group |
---------------------
|  0 |  103 |    27 |
|  1 |  107 |    31 |
|  2 |  103 |    32 |
|  3 |  112 |    31 |
|  4 |  135 |    64 |
|  5 |  135 |    66 |
---------------------

这是组和用户表,如您所见,可以有相同用户和不同组的记录。例如,如何选择具有相同用户和两个组的记录 - 27 和 32?这将是同一个用户。

那么,我该怎么做呢?

编辑:为了显示预期的结果,我写了一个示例:

SELECT user FROM table ... (maybe WHERE group = 27 AND group = 32)

-- 给出用户 id 103

编辑2: 我找到了!

这是对我非常有用的查询:

SELECT * FROM table
WHERE `user` in
(
    SELECT `user` FROM table
    WHERE `group` = <needed_group_1>
)
AND `group` = <needed_group_2>

感谢大家的帮助,我发现您的所有答案都很有用!

4

3 回答 3

2

要获取超过 1 个组的所有数据,请执行

select * from your_table
where `user` in
(
  select `user`
  from your_table
  group by `user`
  having count(distinct `group`) >= 2
)

要获取具有 2 个特定组的数据,请执行

select * from your_table
where `user` in
(
  select `user`
  from your_table
  group by `user`
  having sum(`group` in (27,32)) >= 2
)
于 2013-06-10T10:24:54.753 回答
1

你几乎明白了

尝试这个

  SELECT user FROM table1 WHERE id in ( select `group` = 27 AND `group` = 32
                                      from table1)
  group by user

笔记。:group是保留的 mysql 关键字,所以用反引号将其转义

这将给出:

 USER
 103

在这里演示

于 2013-06-10T10:42:33.150 回答
1
SELECT user
FROM theTable
GROUP BY user
HAVING COUNT(group) = 2

这也可能对您有所帮助:

SELECT
    user,
    COUNT(*) as cnt,
    GROUP_CONCAT(group)
FROM theTable
GROUP BY user

如果您想获取符合您条件的所有记录:

SELECT theTable.*
FROM theTable
JOIN (
    SELECT user
    FROM theTable
    GROUP BY user
    HAVING COUNT(group) = 2
) AS UsersWithTwoGroups USING(user)
于 2013-06-10T10:20:48.843 回答