这是我的表:
+----+-------+------+
| 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 |
+----+-------+------+
我该怎么做?
答案 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