查询基本结构
select * from 表名 where 条件表达式
关于以下各种语法在sql语句中的顺序
这里是引用
使用distinct过滤重复行
select distinct user_name 姓名 from user
Mysql内置数学函数
- ceil(a)为对数值a进行向上取整,如ceil(12.5)的值为13
- fioor(a)为对数值a进行向下取整,如fioor(12.5)的值为12
- round(a)为对数值a进行四舍五入,如round(12.5)的值为13
select user_name 姓名 ceil(user_grade) 成绩 from user; //对成绩进行向上取整
where条件查询
//获取姓名为张三成绩大于85的数据
select user_name 姓名 user_grade 成绩 from user where user_name='张三' and user_grade>85
使用is null和is not null查询空值和非空值
select * from user where user_name is not null chaxun //查询名字不为空的数据
查询结果排序
select * from user order by user_grade asc //成绩升序
select * from user order by user_grade desc //成绩降序
使用limit限制查询结果数量
select * from user limit 3,5 //查询第三条到第五条之间的数据
模糊查询
//" % "通配符,匹配0到多个任意字符。如以下代码可匹配张三,张三三或者任何叫张某某的人
select * from user where user_name like '张%'
//" _ "通配符,匹配一个任意字符。如以下代码只可匹配张三,张四或者任何姓张,名字为一个字段的人
select * from user where user_name like '张_'
//" [] "通配符,方括号内用于指定一个字符或字符合集。详见下表
查询条件表达 | 匹配 |
---|---|
like ‘5[a]’ | 5a |
like ‘5[%]’ | 5%,在[]中%不能作为通配符 |
like ‘5[_]’ | 5_,理由如上 |
like ‘[a,b,c]def’ | adef或bdef或cdef |
like ‘[abc]def’ | adef或bdef或cdef |
like ‘[a-c,A-C]’ | a、b、c、A、B、C |
like ‘abc[_]d%’ | abc_d |
like ‘a[^a]d%’ | ^ a 表示非a字符 |
between···and取两值之间的数据
select * from user where user_grade etween 80 and 90 //获取成绩为80到90的数据
select * from user where user_date etween '1998-08-01' and '1998-09-01' //获取日期为1998-08-01到1998-09-01的数据
Mysql内置聚合函数
select sum(user_grade) from user //查询成绩总和
select max(user_grade) from user //查询成绩最大值
select min(user_grade) from user //查询成绩最小值
select avg(user_grade) from user //查询成绩平均值
select count(user_grade) from user //返回查询结果的行数
select truncate(sum(user_grade),1) from user //查询成绩总和,保留到小数点后一位
分组查询
group by 字段名 [having 条件表达] //[]表示可以不写 having与where用法基本一样
//对班级进行分组,查询各班平均分
select user_banji 班级,avg(user_grade) 班级平均分 from user group by user_banji
//对班级进行分组,查询各班平均分,并新增一行展示各班平均分之和
select user_banji 班级,avg(user_grade) 班级平均分 from user group by user_banji with rollup
联接查询
//设有学生表user,班级表team,将两表同时展示,有以下几种连接方式
//1.内连接
select * from user inner join team on user.Id=team.Id //将两表通过共同字段user.Id连接,inner可省略
//2.左外链接
select * from user left join team on user.Id=team.Id //将左表中的数据与右表进行连接查询
//2.右外链接
select * from user right join team on user.Id=team.Id //将右表中的数据与左表进行连接查询