表结构如下:
select * from book;
+----+------------+------------+
| id | name | pub_date |
+----+------------+------------+
| 1 | 三体 | 2017-08-26 |
| 2 | 三三家的猫 | 1999-05-06 |
| 3 | 三面玲珑 | 2016-09-13 |
| 4 | 三体 | 2016-02-24 |
+----+------------+------------+
4 rows in set
Q1:查询出书名和对应书名的数量;
A1:根据“name”进行分组,然后查询出“name”和“name出现的次数”。
SQL执行顺序:from book --> group by name --> select count(name) num, name
select count(name) num, name from book group by name; +-----+------------+ | num | name | +-----+------------+ | 1 | 三三家的猫 | | 2 | 三体 | | 1 | 三面玲珑 | +-----+------------+ 3 rows in set |
Q2:查询大于1条数据的书籍名称和对应数量;
A2:根据“name”进行分组,然后查询出“name”和“name出现的次数”,然后留下“出现次数大于1的数据”。
SQL执行顺序:from book --> group by name --> select count(name) num, name --> having num>1
拓展:where语句如果要用是放在group by前面的,执行顺序where优先group by;所以此处不适宜用where来判断,having语句是用来判断分组后的数据,where语句只能判断分组前的数据;比如“查询2017年后出版的大于1条数据的书籍名称和对应数量”,见下一题。。。。。。
select count(name) num, name from book group by name having num>1; +-----+------+ | num | name | +-----+------+ | 2 | 三体 | +-----+------+ 1 row in set |
Q3:查询2017年后出版的大于1条数据的书籍名称和对应数量;
A3:查询出版日期在2017年后的数据,然后根据“name”进行分组,然后查询出“name”和“name出现的次数”,然后留下“出现次数大于1的数据”。
SQL执行顺序:from book --> where pub_date>"2017-01-01" --> group by name --> select count(name) num, name --> having num>1
select count(name) num,name from book where pub_date>"2017-01-01" group by name having num>1; Empty set “不查大于1条数据的话,就是有一条数据的” select count(name) num,name from book where pub_date>"2017-01-01" group by name; |
MySQL分页方法 limit
limit m,n
从m+1条数据开始,取n条
从第2条开始,查询2条数据; select * from book limit 1,2; |