一、带AND的条件查询
1.示例:查询字段author为"莫言"的作者,并且书的价格大于40的书籍
select name , author , price from books where author = '莫言' and price > 40;
2.示例:查询字段author为"莫言"的作者,并且书的价格大于40,书名为"丰乳肥臀"的书籍
select name , author , price from books where author = '莫言' and price > 40 and name = '丰乳肥臀';
二、带OR的条件查询
OR就是或的意思,只要满足其中一个条件就会有数据返回
示例:查询字段author为"莫言"的作者或者书的价格大于40的书籍
select name , author , price from books where author = '莫言' or price > 40;
三、查询结果不重复
示例:查询字段author且作者不重复的书籍
select distinct author ,id ,name , price from books;
注意:distinct 放的位置必须是第一列,否则会报错。
四 、简单分组
简单分组的实质是最简单的统计功能,一般而言都是跟聚合函数一起使用的。例如:max() , min() , count() , sum() , avg() , 等聚合函数。
示例:显示每个作者的作品总数
select author , count(*) from books group by author;
查询结果:author表示作者,count(*)表示作者的作品数,group by 字句对数据分组。
五、使用having分组
1.示例:查询作品数大于1的作者
select author , count(name) , from books group by author having count(name) > 1;
2.示例:查询书价格小于60元,作品数大于1的作者
select author , count(name) from books where price < 60 group by author having count(name) > 1;
- 使用having时,必须是分组
- where与having同时出现时,where的优先级高于having
六、Order by查询
示例:查询作者的书籍总价大于100的作者,并按降序排序
select author , sum(price) , from books group by author having sum(price) > 100 order by sum(price) asc;
- 可以看出group by按照作者分组,sum函数返回书的总价格,having对分组数据进行过滤,最后用order by进行排序
- asc:升序排列,desc:降序排列
七、limit限制查询
示例:在表books中,使用limit返回从第4个记录开始,查询5条记录。
select author , price from books limit 3,5;
注:位置下标从0开始