6、 查询 select
6.1 普通查询 select
select * from 表名; #查询整个表
select * from test;
select 内容1 别名1,内容2 别名2 from 表名;
select id 序号, name 名字 from test;
6.2 条件查询 where / having
条件查询: select * from 表名 where 条件;
相等:值1 = 值2;
不相等:值1 != 值2 ; (只有mysql支持) 值1 <> 值2
或者:条件1 or 条件2;
并且: 条件1 and 条件2;
在范围内: in(范围);
不在范围内:not in(范围);
不区分大小写 只有一个字符串的时候‘’ 和“ ” 无区别 嵌套字符串的时候,不能嵌套相同的“ ”, ' " " '
select * from student where S > "04";
select * from student where S <> "04";
select * from student where S = "04" or s = '05';
select * from student where s in('03','05','08','10');
select * from student where s not in('03','05','08','10');
6.3 模糊查询 like
select * from 表名 where 列名 like 模糊表达式
_ : 匹配一个任意字符,“ _雪 _ ” 只能匹配三个字符,并且中间是 雪 的
% :匹配0~n个字符,“%雪%” :只要含有 雪 就匹配
6.4 分页查询 limit
select * from 表名 limit a, b; (a 表示起始位置 b 表示显示多少行 ) 所显示的是不包含 a 的
select * from test limit 3,3;
7、聚合函数
7.1 查个数总和 count()
select count(*) from test where sex = '男';
7.2 求和sum()
select sum(score) from sc where c ='01';
7.3 最大值 max()
select max(score) from sc where c ='01';
7.4 z最小值 min()
select min(score) from sc where c ='01';
7.5 平均值 avg()
select avg(score) from sc where c ='01';
8、分组 group by
group by 分组条件
要查询每个、每组什么的,就按照其分组
group by 在where 之后 , having 之前
#按照学生分组查询学生总成绩
select s,sum(score) from sc group by s;
9、having 和 where 的区别
作为条件的列 是 表中本来就有的,就是用 where
表中没有的列,通过计算得到的新产生的列作为条件时,就用 having
#查询成绩大于60的学生
select s from sc where score > 60 group by s;
#查询总成绩大于200 的学生
select s,sum(score)s1 from sc group by s having s1 > 200;
10、排序 order by
order by 排序列 排序规则
asc : 升序 (默认)
desc: 降序
#按照学生总成绩降序排列
select s from sc group by s order by sum(score) desc;
11、联合查询 ... union all ...;
联合: 查询结果1 union all 查询结果2 ;
select count(sex) from test where sex = '女'
union all
select count(sex) from test where sex ='男';