导图社区 MySQL基本查询-DQL
这是一篇关于MySQL基本查询-DQL的思维导图,包含简单查询、运算符操作、排序查询、聚合查询、分组查询、分页显示、SQL的书写顺序等。
编辑于2024-12-26 16:31:12MySQL基本查询-DQL
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',pname ‘商品名字’,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 is null is not null like
操作
-- 查询商品名称为“海尔洗衣机”的商品所有信息: select * from product where pname = '海尔洗衣机'; -- 查询价格为800商品 select * from product where price = 800; -- 查询价格不是800的所有商品 select * from product where price != 800; select * from product where price <> 800; select * from product where not (price = 800); -- 查询商品价格大于等于60元的所有商品信息 select * from product where price >= 60; -- 查询商品价格在200到1000之间所有商品 select * from product where price between 200 and 1000;
逻辑运算符
符号
and(&&) or(||) not
操作
-- 查询商品价格在200到1000之间所有商品 select * from product where price between 200 and 1000; select * from product where price >= 200 and price <= 1000; select * from product where price >= 200 && price <= 1000; -- 查询商品价格是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;
位运算符(了解)
符号
& | ^ << >> ~
操作
select 3 & 5; -- 位与 0011 0101 --------- 0001 select 3|5; -- 位或 0011 0101 --------- 0111 select 3^5; -- 位异或 0011 0101 --------- 0110 select 3>>1; -- 位右移 0011 >> 1 --->0001 select 3<<1; -- 位左移 0011 << 1 --->0110 select ~1244241242442984858898666; -- 位取反 --18446744073709551612 00000000000000000011 ->111111111111111100
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(*) count(1)
count(pid)
如果列有null值,则不会进行统计
sum()
sum(price)
如果有null值,则不进行计算,当做不存在,列必须为数值列
max()
max(price)
如果有null值,则不进行计算,当做不存在,,列必须为数值列
min()
min(price)
如果有null值,则不进行计算,当做不存在,列必须为数值列
avg()
avg(price)
如果有null值,则不进行计算,当做不存在,列必须为数值列
操作
1:注意,一般情况下,聚合函数和分组会结合在一起用
单独使用
和分组一起使用
5:分组查询
关键字
group by
特点
1:分组可以理解为将一张表临时拆分成多张表,拆分的依据就是分组字段
2:分组可以根据一个字段,也可以根据多个字段,如果是一个字段,则该字段相同就会分到同一组,如果是多个字段,则多个字段都相同才能分到同一组
group by province,city
3:分组之后,select的后边只可以跟分组字段和聚合操作
操作
1:注意,一般情况下,聚合函数和分组会结合在一起用
分组后的条件筛选
1:分组之后,对分组后的结果进行条件判断不能使用where,必须使用having
6:分页显示
关键字
limit
操作
7:SQL的书写顺序
8: SQL的执行顺序
from --->where ---> group by ---->count(pid) ---->having --->select ---->order by ---->limit