我一直在寻找答案的很长时间,我在一个页面中找到了一个很好的解决方案,但是我做得不好,我想知道为什么吗? URL是:http://www.sqlines.com/mysql/how-to/get_top_n_each_group
我遵循的方法,这是我的代码:
SELECT id,
type,
IF (@type = type, @type_rank + 1, 1) AS type_rank,
@type := type
FROM imagesforctool
LIMIT 10
结果是:
id type type_rank @type := type
192499 Men 1 Men
192500 Men 1 Men
192504 Men 1 Men
192508 Men 1 Men
192514 Men 1 Men
192515 Men 1 Men
192516 Men 1 Men
192518 Men 1 Men
192519 Men 1 Men
192520 Men 1 Men
type_rank
列不加。怎么了?
最佳答案
试试这个查询
SELECT
id,
type,
@type_rank := IF(@current_type = type, @type_rank + 1, 1) AS type_rank,
@current_type := type
FROM
imagesforctool
ORDER BY
type
LIMIT
10
关于mysql - MySQL如何获取每个组的前N行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45730907/