我想获得每个类别中第二大和第三大的?这个怎么做 ? 抱歉我的英语不好
我有这样的表 tin_tuc
||id || id_cat ||some information
||1 || 1 ||
||2 || 1 ||
||3 || 1 ||
||4 || 1 ||
||5 || 2 ||
||6 || 2 ||
||7 || 3 ||
||8 || 3 ||
||9 || 3 ||
现在我想获得每个类别的两个记录,它们的值分别为第 2 和第 3(除最大值外的前 3 个)。
我想要的输出
||id || id_cat ||some information
||2 || 1 ||
||3 || 1 ||
||5 || 2 ||
||6 || 2 ||
||8 || 3 ||
||9 || 3 ||
最佳答案
以下查询将根据表格中的类别返回排名靠前的第二和第三首歌曲:
set @num := 0, @category := '';
select
songID, `categoryId`, hits
from
(
select songID, categoryid, hits,
@num := if(@category = `categoryid`, @num + 1, 1) as row_number,
@category := `categoryid` as dummy
from songs
where categoryid is not null
order by `categoryid`, hits desc
) as temptable
where temptable.row_number=3 or temptable.row_number=2;
在这里,我在子查询中按类别和命中率(我的优先级,例如您可以选择您的最高点保持字段)对所有记录进行排序,然后为每条记录提供一个从 1 开始递增的数字,并在类别更改时重置最后我在外部查询中选择第 2 条和第 3 条记录。
关于mysql - 如何选取每个类别的第二条、第三条记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303283/