数据库原理课后练习之单表查询
开门见山
注:数据涉及隐私,自行寻找。表的结构很简单,自行分析下面的语句进行建表,不予提供
1.查询学生姓名和年龄
1 | select s.sname,s.sage from s; |
2.查询班号,姓名,电话
1 | select s.class, s.sname,s.phone from s; |
3.查询学生所有信息
1 | select * from s |
4.查询学生姓名及出生年份
1 | select sname,year(now())-sage as barith from s; |
MySQL:日期函数、时间函数总结,MySQL常用日期时间函数.
5.查询学生姓名(大写),出生年份(别名)
1 | select upper(sname),year(now())-sage as barith from s; |
6.描述每个学生信息,格式如下:
<sname>is from <province>,[He | She]is [young I old],Phonenumber is <pno>
1 | select concat(sname,' is from ',province,' , ',if(ssex='f','She','He'),' is ',if(sage>21,'old','young'),' , ','Phonenumber is ',phone) as info from s; |
7.询班级学生来自哪几个省(去掉重复行)distinct
1 | select distinct province from s; |
8.查询20岁以下的学生 where
1 | select * from s where sage<20; |
9.查询1班20岁以下的男同学 and
1 | select * from s where sage<20 and ssex='m' and class=1; |
10.查询1班20岁男同学或者2班19岁女同学 or
1 | select * from s where (sage=20 and ssex='m' and class=1) or (sage=19 and ssex='f' and class=2); |
11.查询19岁到21岁之间的问学 between…and.…
1 | select * from s where sage between 19 and 21; |
12.查询山西省和河北省的学生in.…
1 | select * from s where province in('shanxi','hebei'); |
13.查询所有姓李的学生 like MySql like模糊查询使用详解,MySQL–更高效的mysql模糊查询的方法
由于库里的名字是拼音,所以推荐用正则 正则表达式 - 语法,揭开正则表达式的神秘面纱,这两篇网页后面真是精妙。
1 | #[]里是声母的开头 {1}应该是多此一举 无法排除lin ling |
14.查询所有使用移动号码的学生
1 | select * from s where phone rlike'^1((3[456789])|47|(5[012789])|78|(8[23478])|198)'; |
15.查询所有未使用移动号码的学生
1 | select * from s where phone not rlike'^1((3[456789])|47|(5[012789])|78|(8[23478])|198)'; |
16.查询没有电话号码的学生 is null
1 | select * from s where phone is null; |
17.查询1班所有学生姓名及年龄,按年龄升序排列 order by
1 | select sname,sage from s where class=1 order by sage; |
18.查询2班所有学生姓名,省份,性别,年龄,结果先按省份排列,同省的再按性别排。同省同性制再按年龄排。
1 | select sname,province,ssex,sage from s where class=2 order by province,ssex,sage; |
19.统计学生人数count
1 | select count(*) from s; |
20.统计学生来自几个省 count
1 | select count(distinct province) from s; |
21.统计学生平均年龄 avg
1 | select avg(sage) from s; |
22.统计学生人数,平均年龄,最大年龄,最小年龄
1 | select count(*),avg(sage),max(sage),min(sage) from s; |
23.统计学生人数(分班统计)
1 | select class ,count(*) from s group by class; |
24.统计学生来自几个省(分班统计)
1 | select class ,count(distinct province) from s group by class; |
25.统计学生平均年龄(分班统计)
1 | select class ,avg(sage) from s group by class; |
26.统计学生人数,平均年龄,最大年龄,最小年龄(分班统计)
1 | select class ,count(*),avg(sage),max(sage),min(sage) from s group by class; |
27.统计学生每个年龄段的人数,只考虑年龄段人数超过3人的,结果按人数高到低排列
1 | select sage ,count(*) as number from s group by sage having number>3 order by 2; |
28.统计学生每个年龄段的人数(分班统计)
1 | select class,sage,count(*) from s group by class,sage; |
29.统计学生每个年龄段的人数(分班分性别统计),只考虑山西省学生,并且分组人数超过3人的
1 | select class,ssex,sage,count(*) from s where province='shanxi' group by 1,2,3 having count(*)>3; |