如何在同一个字段中从具有多个条件的表中选择一条记录?

时间:2013-06-10 10:17:42

标签: mysql select

我有一张这样的表:

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

感谢所有人的帮助,我发现你的所有答案都很有用!

3 个答案:

答案 0 :(得分:2)

获取具有多个组的所有数据

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
)

答案 1 :(得分: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)

答案 2 :(得分:1)

你几乎得到了它

试试这个

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

注意。group是保留的mysql关键字,所以通过反引号来逃避它

这将给出:

 USER
 103

DEMO HERE