select*from 表名 where 范围 -- 选择查询insertinto 表名(field1,field2)values(value1,value2)-- 插入deletefrom 表名 where 范围 -- 删除update 表名 set field1=value1 where 范围 -- 更新select*from 表名 where field1 like ’%value1%’ -- 查找select*from 表名 orderby field1,field2 [desc]-- 排序:select count as 需要统计总数的字段名 from 表名 -- 总数selectsum(field1)as sumvalue from 表名 -- 求和selectavg(field1)as avgvalue from 表名 -- 平均selectmax(field1)as maxvalue from 表名 -- 最大selectmin(field1)as minvalue from 表名 -- 最小
# between 在...之间select id,name from emp where id >=3and id <=6;
相当于:
select*from emp where id between3and6;# or 或者select*from emp where id >=3or id <=6;# in,后面可以跟多个值select*from 表名 where 字段名 in(条件1,条件2,条件三);# like (见上18)# char——length() 取字符长度select*from 表名 where char_length(需要获取长度的字段名)=4;not 配合使用
注意:判断空不能用 = ,只能用 is
(2)group by 分组
select 查询字段1,查询字段2,...from 表名
where 过滤条件
groupby分组依据 # 分组后取出的是每个组的第一条数据
(3)聚合查询 :以组为单位统计组内数据>>>聚合查询(聚集到一起合成为一个结果)
# max 最大值# 每个部门的最高工资select post,max(salary)from emp groupby post;# min 最小值# 每个部门的最低工资select post,min(salary)from emp groupby post;# avg 平均值# 每个部门的平均工资select post,avg(salary)from emp groupby post;# 每个部门的工资总和# sum 求和select post,sum(salary)from emp groupby post;# count(需要计数字段) 计数# 每个部门的人数select post,count(id)from emp groupby post;# group_concat(需要分组后的字段) # 不仅可以用来显示除分组外字段还有拼接字符串的作用select post,group_concat(name)from emp groupby post;-- post:分组字段,name 需要分组后显示的字段
拼接:
concat(不分组时用)拼接字符串达到更好的显示效果 as语法使用
举例:
select concat("NAME: ",name)as 姓名 from emp;
concat_ws: 如果拼接的符号是统一的可以用
举例:
select concat_ws(':',name,age,sex)as info from emp;
group_concat:
举例:
select post,group_concat(name,'DSB')from emp groupby post;
补充:as语法 起别名
select name as 姓名,salary as 薪资 from emp;
(4)having 过滤查询
# having的语法格式与where一致,只不过having是在分组之后进行的过滤,即where虽然不能用聚合函数,但是having可以!# 用法select 查询字段1,查询字段2,...from 表名
where 过滤条件1groupby分组依据
havingavg(过滤条件2)>10000;
replace(str1,old,new)-- str1:需要替换的字段名update gd_km set mc=replace(mc,'土地','房子')
说明:new替换str1中出现的所有old,返回新的字符串,如果有某个参数为NULL,此函数返回NULL
该函数可以多次替换,只要str1中还有old存在,最后都被替换成new
若new为空,则删除old
4.多表查询
(1).内连接、左连接、右连接、全连接
1、内连接:只取两张表有对应关系的记录(只拼两个表共有的)
左表 innerjoin 右表 on 条件
select*from emp innerjoin dep on emp.dep_id = dep.id
where dep.name ="技术";2、左连接:在内连接的基础上,保留左边的数据,右边没有就为空
左表 innerleft 右表 on 条件
3、右连接:在内连接的基础上,保留右边的数据,左边没有就为空
左表 innerright 右表 on 条件
4、全连接:左右连接都有,用union连接
左表 innerleft 右表 on 条件 union 左表 innerright 右表 on 条件
select*from emp leftjoin dep on emp.dep_id = dep.id
unionselect*from emp rightjoin dep on emp.dep_id = dep.id;
(2).子查询
# 就是将一个查询语句的结果用括号括起来当作另外一个查询语句的条件去用select name fromwhere id in(select dep_id from emp where age>25);
综合使用 查询 目录#----综合使用书写顺序select distinct * from '表名' where '限制条件' group by '分组依据' having '过滤条件' order by limit '展示条数'执行顺序from -- 查询where -- 限制条件group by -- 分组having -- 过滤条件order by -- 排序limit -- 展示条数distinct -- 去重selec