如何选择具有相同值的所有行

时间:2015-12-27 01:14:14

标签: mysql

这是我的表:

+----+-------+------+
| id | name  | code |
+----+-------+------+
| 1  | jack  | 1    |
| 2  | peter | 1    |
| 3  | jack  | 1    |
| 4  | ali   | 2    |
| 5  | peter | 3    |
| 6  | peter | 1    |
| 7  | ali   | 2    |
| 8  | jack  | 3    |
| 9  | peter | 2    |
| 10 | peter | 4    |
+----+-------+------+

我想选择满足的所有行:{code值在1-3之间且其name值相同的那些行的数量}大于或等于4

从上面的数据中,我想要这个输出:

+----+-------+------+
| id | name  | code |
+----+-------+------+
| 2  | peter | 1    |
| 5  | peter | 3    |
| 6  | peter | 1    |
| 9  | peter | 2    |
+----+-------+------+

我该怎么做?

1 个答案:

答案 0 :(得分:4)

使用子查询确定应返回哪些名称,然后在其上构建主查询。

试试这个:

select *
from mytable
where name in (
    select name
    from mytable
    where code between 1 and 3
    group by name
    having count(*) > 3)
and code between 1 and 3