MySQL找到每个组的顶部结果 [英] MySQL find top results for each group

查看:88
本文介绍了MySQL找到每个组的顶部结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了很多,但我找不到答案或附近的东西。



我有一个这样的表:

  )NO PRI auto_increment 
attribute_id int(11)YES
user_id int(11)YES
result int(11)YES
x10 int(11)YES

我需要每个 attribute_id 约5个结果。



attribute_id 可以是任何数字,因此首先,我需要检查 attribute_id ,接下来我必须检查每个attribute_id的结果。



我没有找到我除了MySQL之外没有任何编程语言,但我知道你可以这样做。



示例:

  attribute_id结果
1 200
1 149
1 123
2 322
2 321
2 300
3 ...
3 ...



等等。

解决方案

  SELECT attribute_id,result 
FROM TableName a
WHERE

SELECT COUNT(*)
FROM TableName b
WHERE a.attribute_id = b.attribute_id
AND a.result< = b.result
)< = 5




I have searched a lot, but I can't find an answer or something near.

I have a table like this:

id              int(11) NO  PRI     auto_increment
attribute_id    int(11) YES         
user_id         int(11) YES         
result          int(11) YES             
x10             int(11) YES 

I need about 5 results from each attribute_id.

attribute_id can be any number, so at first, I need to check for the attribute_id, and next I have to check for the results for each attribute_id.

I can't find out how I do this without any programming language other than MySQL, but I know you can.

Example:

attribute_id    result
1               200
1               149
1               123
2               322
2               321
2               300
3               ...
3               ...

And so on.

解决方案

SELECT  attribute_id, result
FROM    TableName a
WHERE 
        (
            SELECT  COUNT(*) 
            FROM    TableName b
            WHERE   a.attribute_id = b.attribute_id 
                    AND a.result <= b.result
        ) <= 5

这篇关于MySQL找到每个组的顶部结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆