MySql中group by, order by,按照出现频率排序
MySql 中 group by, order by 基本用法,分组按出现次数排序
·
#环境及运行[0],示例表结构:
CREATE TABLE t (
val int,
name char(10)
);
#表中数据:
INSERT INTO t
(val, name)
VALUES
(10, 'xyb'),
(20, 'xyb'),
(30, 'charlotte'),
(40, 'xyb'),
(50, 'charlotte'),
(60, 'charlotte'),
(70, 'xyb'),
(80, 'xl'),
(90, 'xyb'),
(100, 'xl'),
(110, 'charlotte'),
(120, 'bozai'),
(130, 'charlotte'),
(140, 'xyb'),
(150, 'bozai'),
(160, 'xl'),
(170, 'xl'),
(180, 'bozai'),
(190, 'charlotte'),
(200, 'xyb'),
(210, 'xyb'),
(220, 'love'),
(230, 'love'),
(240, 'bozai'),
(250, 'xyb'),
(260, 'charlotte'),
(270, 'xl'),
(280, 'charlotte'),
(290, 'xl'),
(300, 'love');
group by 对查询到的记录按照某个列进行归类,输出该列值第一次出现的值对应的记录,默认对该列进行升序排列。
SELECT name, val FROM t
GROUP BY name
输出结果:
name | val |
---|---|
bozai | 120 |
charlotte | 30 |
love | 220 |
xl | 80 |
xyb | 10 |
order by 对查询到的记录按照一个或多个列排序,默认为升序,会返回所有结果。查询语句:
SELECT name, val FROM t
ORDER BY name DESC;
查询结果:
name | val |
---|---|
xyb | 10 |
xyb | 200 |
xyb | 90 |
xyb | 210 |
xyb | 70 |
xyb | 250 |
xyb | 40 |
xyb | 20 |
xyb | 140 |
xl | 270 |
xl | 290 |
xl | 170 |
xl | 160 |
xl | 80 |
xl | 100 |
love | 300 |
love | 230 |
love | 220 |
charlotte | 190 |
charlotte | 30 |
charlotte | 280 |
charlotte | 50 |
charlotte | 260 |
charlotte | 60 |
charlotte | 110 |
charlotte | 130 |
bozai | 240 |
bozai | 150 |
bozai | 120 |
bozai | 180 |
group by 优先级比 order by 高,连用时候通常 group by 写在 order by 前面,此时 order by
处理的是 group by 选择之后的记录。查询语句:
SELECT name, val FROM t
GROUP BY name
ORDER BY val DESC;
查询结果:
name | val |
---|---|
love | 220 |
bozai | 120 |
xl | 80 |
charlotte | 30 |
xyb | 10 |
在 select 语句中使用条件判断用 where 语句,对 group by 的结果做条件判断用 having 语句,可以使用别名(alias),查询语句:
SELECT val, name , count(*) AS cnt FROM t
GROUP BY name having cnt > 6
ORDER BY val DESC;
返回相同 name 值出现过超过6次的记录,并对这些记录按照 val 的值进行降序排序。查询结果:
val | name | cnt |
---|---|---|
30 | charlotte | 8 |
10 | xyb | 9 |
而别名还可以作为排序或者统计的一个指标,这使得分类别,然后按照频率来统计非常方便[1],查询语句:
SELECT val, name , count(*) AS cnt FROM t
GROUP BY name
ORDER BY cnt DESC;
查询结果:
val | name | cnt |
---|---|---|
10 | xyb | 9 |
30 | charlotte | 8 |
80 | xl | 6 |
120 | bozai | 4 |
220 | love | 3 |
此外在stack overflow上还看到一种方式,利用连表查询,查询语句[2]:
SELECT DISTINCT t.name, t2.cnt cnt
FROM t
INNER JOIN ( SELECT name, COUNT(*) AS cnt
FROM t
GROUP BY name
) t2 ON ( t2.name = t.name )
ORDER BY t2.cnt DESC;
查询结果:
name | cnt |
---|---|
xyb | 9 |
charlotte | 8 |
xl | 6 |
bozai | 4 |
love | 3 |
参考链接:
[0]http://sqlfiddle.com/#!2/4123be/4
[1]http://stackoverflow.com/questions/8100239/mysql-order-by-count
[2]http://stackoverflow.com/questions/2283305/order-by-count-per-value
更多推荐
已为社区贡献1条内容
所有评论(0)