Ifnull(‘null’,’ok’)输出ok null是空,所以输出ok
Ifnull(‘yes’,’no’)yes不是null 所以输出原值
curdate() :返回当前日期
Day()函数取出day的值
%代表0个或多个字符
消除重复
插入查询结果
分组查询:
select dept ,count(*),max(score),min(score),sum(score)
from s
where score>60
group by dept having count(*)>1---查询专业人数,最高成绩,最小成绩综合成绩当成绩大于60根据专业分组
select *from s where score in (select max(score)from s)---查询最好成绩的所有信息(子查询)
select ss.lv,count(*)from
(select dept,id ,name,score,if(score>90,'优',if(score>=80,'良',if(score<60,'补考','及格')))lv from s)ss group by ss.lv
select count(distinct dept) from s
select max(score),min(score),avg(score),sum(score),count(score)from s
select row_number() over(order by score desc ) id,score ,name from s--根据成绩排名
select name into outfile 'd:/usr.txt'from s --将查询结果导入文件
round(rand(),0)--写0是取整,其他数字是小数
select dept,count(*)from s group by dept-- 根据专业分组并显示专业总人数
having 过滤 where紧跟表名
--集合函数中where不能直接应用条件
Row_number():依次递增排名,无重复排名
Rank()间断排名,重复排名
Dense_rank() 依次递增排名,有重复排名
Ntile():分组排名
分区函数Partition By
As :代表别名
连接查询
select id,name from s order by id asc --升序排列
select id ,name ,dept from s order by name desc ---名字按降序排列
select id ,name ,dept from s order by dept desc ,name asc---先按专业排序,专业相同按名字升序排列
select *from(
select row_number() over(partition by dept order by score desc ) as m ,s.*from s) where m=1 --查询各专业中成绩按降序排名(每一个派生表都必须有他自己的别名) -- select * from 表名 where 条件 group by 分组 having 分组条件 order by 排序
limit 限制结果行数 子查询
select *from
(
select row_number() over( partition by dept order by score DESC)as a ,s.*from s)as t where a<=2
select id ,name from s
select id,name from s limit 3 /* 限制结果行数,查询排序*/ -- 第n页 limit n*3-3,3
select id ,name from s limit 3,3
select num ,count(*) from
(select if(score>90,'优秀',if(score>=80,'良',if(score>60,'及格','不及格')))as num ,s.*from s )as a
select id 编号,
name 姓名,
ifnull('score',0) 分数,
if(score>90,'优秀',if(score>=80,'良',if(score<60,'不及格','及格'))) from s
select level 等级,count(*) from (
select id ,name ,score,case
when score>90 then '优秀'
when score>50 then '良'
when score <50 then '不及格'
else '补考' end level
from s )as t group by t.level
-- 联合查询
UNION ALL 命令和 UNION 命令几乎是等效的,不过 UNION ALL 命令会列出所有的值。
select name from s
union all
select id from t1
select *from (select 1,2,3) as t1, (select 1,3,2)as t2-- 多表查询
SELECT s.id ,s.name,t.id,t.name from s s ,t1 t where s.id=t.id-- 查询学生的信息,及这个学生老师的名字
select *from s inner join t1 on s.id=t1.id -- INNER JOIN 关键字在表中存在至少一个匹配时返回行。相当于一个联合查询
join using 后面接 两张表中都存在的字段 (字段名称 一样)
join on 后面接 两张表中中需要关联的字段 (字段名称不需要一样 a.id = b.id
select s.id ,s.name, s.score , s.birth s left join t1 on s.id=t1.id-- 左连接查询 链接查询比多表查询效率高
-- 左连接查询侧重于显示join左边表内的所有数据,右链接侧重于显示join右边
-- 左连接查询侧重于显示join左边表内的所有数据,右链接侧重于显示join右边
-- 自然连接查询消除重复