#环境及运行[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 

输出结果:

nameval
bozai120
charlotte30
love220
xl80
xyb10

order by 对查询到的记录按照一个或多个列排序,默认为升序,会返回所有结果。查询语句:

SELECT name, val FROM t
ORDER BY name DESC;

查询结果:

nameval
xyb10
xyb200
xyb90
xyb210
xyb70
xyb250
xyb40
xyb20
xyb140
xl270
xl290
xl170
xl160
xl80
xl100
love300
love230
love220
charlotte190
charlotte30
charlotte280
charlotte50
charlotte260
charlotte60
charlotte110
charlotte130
bozai240
bozai150
bozai120
bozai180

group by 优先级比 order by 高,连用时候通常 group by 写在 order by 前面,此时 order by
处理的是 group by 选择之后的记录。查询语句:

SELECT name, val FROM t 
GROUP BY name 
ORDER BY val DESC;

查询结果:

nameval
love220
bozai120
xl80
charlotte30
xyb10

在 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 的值进行降序排序。查询结果:

valnamecnt
30charlotte8
10xyb9

而别名还可以作为排序或者统计的一个指标,这使得分类别,然后按照频率来统计非常方便[1],查询语句:

SELECT val, name , count(*) AS cnt FROM t
GROUP BY name
ORDER BY cnt DESC;

查询结果:

valnamecnt
10xyb9
30charlotte8
80xl6
120bozai4
220love3

此外在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;

查询结果:

namecnt
xyb9
charlotte8
xl6
bozai4
love3

参考链接:
[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

Logo

更多推荐