1.简单的查询
查全表
select * from product;
按指定字段查询
select pid, pname , price from product;
别名查询:
列别名:
select pid as '商品id',pname '商品名字',price from product;
select pname,price+10 as new_price from product;
表别名
select pid as '商品id',price from product as p;
去重查询;
关键字:
distinct
操作:
去除重复行
select distinct * from product;
去重重复列
select distinct price from product;
2.运算符操作:
算数运算符
符号:
+ - * / %
操作:
select 1+2;
select price*1.1 from product;
比较运算符
符号:
> >= < <= != in not in like
操作:
1.查询商品价格为800的商品:select * from product where price = 800;
2.查询商品价格不是800元的所有商品:
select * from product where price !=800;
select * from product where price <> 800;
select * from product where not(price = 800);
3.查询商品价格大于等于60元所有的商品信息:
select * from where price >60;
4.查询商品价格在200到1000之间的所有商品;
select * from product where price between 200 and 1000;
逻辑运算符
and (&&) or (||) not
操作:
1. 查询商品价格在200到1000之间的所有商品:
select *from product where 20 and 1000;
select * from product where price >=200 and price <=1000;
select * from prodect where price >=200 && price<=1000;
2.查询商品价格是200或者800的所有商品:
select *from product where price in(200,800);
select * from product where price =200 or price = 800;
select * from product where price=200 || price = 800;
位移运算符(了解)
符号;
& | ^ << >> ~
操作:
3.排序查询:
关键字:
order by asc| desc
asc升序(默认)
desc降序;
特点
1.如果order by只跟一个字段,则只会按照该字段的值进行排序,该字段必须为数值类型或者英文和数字字符串类型('beijing')或者'2020-12-23'。
2.如果order by 后面有多个字段:order by c1,c2解释:先按照c1来排序如果c1相同则按照c2进行排序。
操作:
4.聚合查询;
关键字:
count()
count(1) count(*) count(pid)
count(pid)
如果有null值,则不会进行统计
sum()
sum(price)
如果有null,则不进行计算,当作不存在,列必须为数值列。
max()
max(price)
如果有null,则不进行计算,当作不存在,列必须为数值列。
min()
min(price)
如果有null,则不进行计算,当作不存在,列必须为数值列。
avg()
avg(prive)
如果有null,则不进行计算,当作不存在,列必须为数值列。
操作:
1.注意:一般情况下,聚合函数和分组会一起结合使用
单独使用:
和分组一起使用:
5.分组查询:
关键字:
group by
特点:
1.分组可以理解为将一张表临时拆分成多张表,拆分的依据就是分组字段
2.分组可以根据一个字段,也可以根据多个字段,如果值一个字段,则该字段相同就会分到同一组,如果是多个字段,则多个字段相同才能分到同一组。
3.分组之后,select 的后边只能跟分组字段和聚合进行操作
操作:
1.注意:一般情况下,聚合函数和分组会结合一起使用
分组后的条件筛选
1.分组之后,对分组后的结果进行条件判断时不能使用where ,必须要使用having
6.分页显示:
关键字
limit
操作:
7.SQL的书写顺序:
8.SQL的执行顺序:
from—>where—>group by—>count(pid)---->having---->select----->order by