数据库查询
-
基本语法
格式:select * from 表名;
说明:select 后跟要查询的内容(字段名),*代表查询全部,from代表数据来源于哪张表
示例:select name,id from student;
-
消除重复行
在select跟字段之间使用distinct可以消除重复的行。
示例:select distinct name from student;
-
条件查询
a、语法:select * from 表名 where 条件;
b、比较运算符:+,-,*,、,=,!=,<,>,%
示例:select * from 表名 where id<18;
c、逻辑运算符
and 并且 select * from student where id>7 and gender=0;
or 或者 select * from student where id>7 or gender=0;
说明:只要满足任意条件都会匹配出来
not 不是 select * from student where id>7 not gender;
d、模糊查询
示例:select * from student where name llike ‘%a%’;(只要包含a就会匹配出来)
说明:%代表包括空白在内的任意字符,_代表一个字符
e、范围查询
in 在 select * from student where id in (1,3,4);
not in 不在 select * from student where id not in (1,3,4);
between and select * from student where id between 6 and 8;
f、空判断
insert into student(name,age) values(‘小明’,70);
说明:null 与’'不同
select * from student where address is null;(或者is not)
g、优先级
小括号,not 比较运算符,逻辑运算符
and 比 or 优先级高,如果同时出现并希望先选or,需要结合()使用
-
聚合查询
a、count(*) 表示计算总行数,括号中可以写**和字段
b、max(字段) 表示求此列的最大值
c、min(字段) 表示求此列的最小值
d、sum(字段) 表示求此列的和
e、avg(字段) 表示求此列的和
select max(age) from student where gender=‘0’;
-
分组查询
按照字段分组,表示此字段相同的数据会被放到一个集合中。
分组后,只能查询相同的数据列,对于有差异的数据列无法显示在结果集中,可以对分组数据进行统计,做聚合运算。
语法:select 列1,列2,聚合…… from 表 group by 列1,列2,……
示例:查询男女生总数
select gender,count(*) from student group by gender;
分组后的数据筛选:
select 列1,列2,聚合…… from 表 group by having 列1,列2,……,聚合…… having 条件
示例:select gender,count(*) from student group by gender having gender=0;
where和having的区别:
where是对from后面指定的表进行筛选,属于对原始表的筛选
having是对group by的结果进行筛选
示例:select id,name from teachers where name in (select name from teachers group by names having count(name)>1);
-
排序
语法:select * from 表名 order by 列1 asc| desc,列2 asc|desc;
说明:将数据按照列1进行排序,如果某些列1的值相同,那么按照列2排序
默认按照升序排列,asc降序,desc降序
-
分页
语法:select * from 表名 limit x,y;
说明:从第x+1行开始,查询y行内容