查询
select 字段 from 表名 where 条件
关系运算符
=,>,<,>=,<=,!=,<>
其中!=和<>均为不等于
查询条件
1.in或not in查询
in:字段在集合的范围内
not in:字段不在集合的范围内
select * from 表名 where 字段 in ('1','2');
2.between and查询
between and:表示字段的值在指定的范围内
not between and: 表示字段的值不在指定的范围内
select * from 表名 where 字段 between 2 and 5;
3.null值查询
null:代表空 not null代表非空
select * from 表名 where 字段 is null;
4.distinct查询
distinct代表过滤重复值
select distinct 字段 from 表名 where 条件;
5.like查询
like代表包含关键字的模糊查询 not like代表不包含关键字模糊查询
%代表通配符,_代表一个字符
select * from 表名 where 字段 like '%关键字%';
6.and查询
and代表并查询
select * from 表名 where 字段1=‘’ and 字段2='';
7.or查询
or代表或查询
select * from 表名 where 字段1=‘’ or 字段2='';
and和or 同时存在,and优先级高
聚合函数
1.count():查询总数
select count() from 表名;
2.sum():求和
select sum(字段) from 表名;
3.avg():求平均值
select avg(字段) from 表名;
4.max():求最大值
select max(字段) from 表名;
5.min():求最小值
select min(字段) from 表名;
排序
asc | 升序 |
---|---|
desc | 倒序 |
select * from 表名 order by 字段; --默认升序排列
分组
select * from 表名 group by 字段;
select count(*),字段 from 表名 group by 字段;--分组一般和聚合函数一起使用
select sum(字段),字段 from 表名 group by 字段 having sum(字段)>100;
limit限量
select * from 表名 limit 3,4;--代表从第4个记录开始查询四条记录
limit后第一个参数代表偏移量,从0开始,0代表第一条记录,1代表第二条记录。第二个参数代表查询记录的条数。
别名
可以用AS 或者省略取别名
多表查询
1.交叉连接
交叉连接返回的结果是两个表中所有数据的笛卡儿积。例如:
部门表有4个部门,员工表有3个员工,那么交叉的结果就是4*3=12条数据
此种查询在实际业务中很少用到
select * from 表1 cross join 表2;
2.内连接
内连接返回的结果是满足比较运算结果的数据
select * from 表1 inner join 表2 on 表1.did=表2.did;--其中inner可省略
MySQL可以使用where实现同样的功能
select * from 表1, 表2 where 表1.did=表2.did;
区别:
where条件后边可以跟其他条件,但是内连接不可以
3.外连接
外连接又分为左连接和右连接
select * from 表1 left|right join 表2 on 表1.did=表2.did where 条件;
- 左连接是返回左表中所有记录和右表中符合连接条件的记录
- 右连接是返回右表中所有记录和左表中符合连接条件的记录
子查询
1.in或not in
in查询时,内层语句仅返回一个数据列,这个数据列的值将供外层查询语句进行比较操作。
例如:查询年龄为20岁的员工部门
select * from 部门 where did in (select did from 员工 where 员工.年龄=20);
not in正好和in相反
2.exists
exists后边参数可以是任意一个子查询,这个查询结果只返回true或false,当返回true时,外层语句才会执行
例如:查询员工是否存在大于20岁的,如果存在则处查询部门信息
select * from 部门 where exists (select did from 员工 where 员工.年龄>20);
exists比in的运行效率高,大量数据推荐使用exists
3.any
any表示满足其中任意一个条件作为外层的查询条件
例如:查询满足条件的部门
select * from 部门 where did >any(select did from 员工);
4.all
all表示满足所有内层条件
例如:查询满足条件的部门
select * from 部门 where did >all(select did from 员工);
网友评论