-- MySQL分組排序取前N條記錄的最簡潔的單條sql。
N>(
結果如下:
mysql> SELECT * FROM (SELECT cid,author,COUNT(*) AS number FROM test GROUP BY cid,author) a -> WHERE -> 3>( -> SELECT COUNT(*) -> FROM (SELECT cid,author,COUNT(*) AS number FROM test GROUP BY cid,author) b -> WHERE a.cid=b.cid AND a.number<b.number -> )ORDER BY cid,number DESC; +------+----------------+--------+ | cid | author | number | +------+----------------+--------+ | 1 | test3 | 4 | | 1 | test2 | 3 | | 1 | test1 | 2 | | 2 | test33 | 4 | | 2 | test22 | 3 | | 2 | test11 | 2 | | 200 | 200test_nagios | 1 | +------+----------------+--------+ 7 rows in set (0.00 sec)
N就是取分組之後的最前面幾個判斷,N=3就是取前3個
-- 生成自動數字序列
SET @ROW=0;