mysql查询2

来源:互联网 发布:国外个人java技术博客 编辑:程序博客网 时间:2024/06/05 06:13

单表查询:
1选择列
select * from xs;
select 学号,姓名 from xs;
select 学号 as sno,姓名  as name  from xs;
select 学号,总学分*1.2 as 新学分 from xs;

select 姓名,case
when 性别=1 then '男'
when 性别=0 then '女'
end  as 性别,专业名
from xs;

2  选择行

where条件
1)比较运算符:= >  >=   <   <=  <>   !=  <=>

2) 逻辑运算符    and   &&     or  ||  not  !

查找计算机系的男学生的信息
select * from xs  where  专业名='计算机' and  性别=1

3)模式匹配:like    %   _
select * from xs where 姓名 like '王%';                  '王_'


4)范围比较
between  :成绩 between 80 and 90     (成绩 >=80  and 成绩<=90)
not  between   :  select * from xs_kc  where  成绩  not between  80 and 90


查看产地是广州,上海,北京的产品信息
select * from product
where 产地='广州' or 产地='上海' or  产地='北京';
in:     产地  in ('广州','上海','北京')
查看关键字与列表中的任何一个值匹配,就返回true

not in:      产地 not in ('广州','上海','北京')


5)空值比较
is  null
is not null

select * from xs where 备注 is not null;


6)去掉重复的行:distinct

select  distinct 专业名 from xs;

 

3 对查询结果排序
order by 子句:
升序:asc  (默认)
降序:desc
如果是按多个字段排序,先按第一个字段排,当第一个字段的值相同时,在按第二个排。


4 limit子句:限制结果集中的行数

一般limit子句放在select语句的最后
limit 5   :表示返回结果集的前面5条记录
limit 3,5:表示返回从第4行开始的5条记录

 

4 分组:分类汇总
聚合函数:
count(*):统计记录的条数 
count(字段名):统计字段中有值的记录个数。(不考虑null)
count(distinct 字段名): 去掉重复值后在计算有值的个数

max(字段名):计算某一列最大值
min(字段名):计算某一列最小值

sum(字段名):求和
avg(字段名):求平均值


统计xs表中的记录数:select count(*) from xs

查询选修了课程的学生人数
select count(distinct 学号) as 人数 from xs_kc;

查询选修101课程的学生的最高分

select max(成绩) as 最高分 from xs_kc
where 课程号=101;


分组:group by 字段名:
根据字段的值对记录进行分组

group  by 性别

select 性别,count(*) as 人数 from xs
group by 性别;

分组后可以看哪些字段:一般是分组的字段,和使用聚合函数的列。

group by 字段名1,字段名2

select 专业名,性别,count(*) as 人数
from xs
group by 专业名,性别
with rollup;

 

查询平均分是大于77的课程号,和相应的平均分。

select 课程号,avg(成绩) as 平均分
from xs_kc
group by 课程号
having avg(成绩)>77;

使用分组后在进行挑选   having关键字

having 与where的区别:where是对原始记录进行挑选,跟在from后。
having:对分组后的记录进行挑选,跟在group by 后。

select 学号  from xs_kc
where 成绩>=80
group by 学号
having count(*)>2

查询每个学生的学号和选课数
select 学号,count(*) as 选课数
from xs_kc
group by 学号;


查询选修了2门课程以上的学生学号。

select 学号
from xs_kc
group by 学号
having count(*)>2;


查询每门课程号及其选课人数。

select  课程号,count(*) as 人数
from xs_kc
group by 课程号;

 

原创粉丝点击