如何扩展按查询分组的所有值?

时间:2019-03-16 16:40:00

标签: mysql

我正在尝试按计数从组中获取行。我的情况是pid应该计数为5,但pid的值无论如何。

select pid,count(*) from similar where pattern_len=5 group by id limit 5;

这将给出以下结果

| 1a4m_D |        4 |
| 1a4o_A |        2 |
| 1a4o_B |        2 |
| 1a4o_C |        2 |
| 1a4o_D |        2 |

现在我正在尝试获取与那些条件匹配的所有行,因此对于我上面的查询,它将给出12行(4 + 2 + 2 + 2 + 2 + 2)。(我正在尝试获取所有我正在尝试不同的查询,但没有得到任何结果。我该怎么解决?

样本输入

+--------+-------------+---------+----------------------------+-------------+----------------------------+
| pid     | pattern_len | pattern | pattern_range              | range_count | position                   |
+--------+-------------+---------+----------------------------+-------------+----------------------------+
| 1a4m_D |           5 | aaaaa   | [7 to 11] [8 to 12]        |           2 | [7 to 11] [8 to 12]        |
| 1a4m_D |           5 | aaaaa   | [5 to 9] [6 to 10]         |           2 | [5 to 9] [6 to 10]         |
| 1a4o_B |           5 | aaaaa   | [122 to 126] [123 to 127]  |           2 | [122 to 126] [123 to 127]  |
| 1a4o_B |           5 | aaaaa   | [26 to 30] [226 to 230]    |           2 | [26 to 30] [226 to 230]    |
| 1a4o_B |           5 | aaaaa   | [3 to 7] [4 to 8]          |           2 | [3 to 7] [4 to 8]          |
+--------+-------------+---------+----------------------------+-------------+----------------------------+

1 个答案:

答案 0 :(得分:0)

您没有说出哪个MySQL版本,但是您可以在MySQL 8.x中做到。

首先,您需要为ORDER BY添加一个LIMIT才有意义。然后,此查询应扩展子选择:

with
y as (
  select pid 
  from similar 
  where pattern_len = 5
  group by pid
  order by count(*) desc
  limit 5
)
select * 
from similar
where pid in (select pid from y)