Home > Database > Mysql Tutorial > MySQL分组排序取前N条记录以及生成自动数字序列的SQL_MySQL

MySQL分组排序取前N条记录以及生成自动数字序列的SQL_MySQL

WBOY
Release: 2016-06-01 13:17:57
Original
1247 people have browsed it

bitsCN.com -- 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)
Copy after login

N就是取分组之后的最前面几个判断,N=3就是取前3个

 -- 生成自动数字序列
SET @ROW=0;

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template