Mysql group by top N的問題 在日常工作中,經常要查詢分組的前幾名.oracle中可以通過row_num來支持查詢,mysql暫時不支持row_num.那麼如何來完成這個需求呢? 例如: 表中的數據:
+--------+-------+-----+ | Person | Group | Age | +--------+-------+-----+ | Bob | 1 | 32 | | Jill | 1 | 34 | | Shawn | 1 | 42 | | Jake | 2 | 29 | | Paul | 2 | 36 | | Laura | 2 | 39 | +--------+-------+-----+
期望的結果:
+--------+-------+-----+ | Shawn | 1 | 42 | | Jill | 1 | 34 | | Laura | 2 | 39 | | Paul | 2 | 36 | +--------+-------+-----+
方式一:借鑒oracle中row_num的思想,在sql中增加偽列.
set @num := 0, @group := ''; select person, `group`, age from ( select person, `group`, age, @num := if(@group = `group`, @num + 1, 1) as row_number, @group := `group` as dummy from mytable order by `Group`, Age desc, person ) as x where x.row_number <= 2;
方式二:利用關聯子查詢
SELECT a.person, a.group, a.age FROM person AS a WHERE (SELECT COUNT(*) FROM person AS b WHERE b.group = a.group AND b.age >= a.age) <= 2 ORDER BY a.group ASC, a.age DESC