MySql获得每个父ID的最高计数

时间:2016-11-07 11:13:16

标签: mysql

ID    item_ID    parent_ID   count
================================
1      11          2          5
2      12          2          6
3      13          3          2
4      14          3          3
5      15          2          7
6      16          1          3

SELECT * FROM relations ORDER BY count DESC

应该返回的行是2,4和6,因为它们的parent_ID

计数最高

如何更改查询以完成此操作?

1 个答案:

答案 0 :(得分:1)

内部选择获得每个parent_ID的最高计数。如果您加入,则过滤掉相关记录

select t1.*
from your_table t1
join
(
    select parent_ID, max(count) as mcount
    from your_table
    group by parent_ID
) t2 on t1.parent_ID = t2.parent_ID
    and t1.count = t2.mcount