1、建立student、achievement表函數
1. create table student(id int unsigned auto_increment primary key,name varchar(30),sex varchar(3) not null default 'nan');spa
2. create table achievement(id int unsigned auto_increment primary key,result int(3));rem
3. insert into student(name,sex)io
select 'zaho si','nan' from dual uniontable
select 'zaho hong','nv' from dual unionclass
select 'wang hong','nv' from dual unionselect
select 'wang er','nan' from dual unionnio
select 'zaho si','nan' from dual unionim
select 'feng yi','nan' from dual union查詢
select 'feng yi','nv' from dual;
4. insert into achievement(result)
select 80 from dual union
select 90 from dual union
select 80 from dual union
select 50 from dual union
select 80 from dual union
select 60 from dual union
select 100 from dual;
2、聚合用函數(count,sum,max,min,avg等)的使用
1. 平均成績: select avg(result) as avg_achievement from achievement;
2. 最好成績: select max(result) max_achievement from achievement;
3. 'wang'姓人列表:select * from student where name like "wang%";
4. 'wang'姓人數:select count(name) wang from student where name like 'wang%';
注:使用like模糊查詢時,%匹配0或多個字符,_匹配單個字符
3、分組聚合查詢
1. 男女各多少人: select sex,count(sex) from student group by sex;
4、多表查詢
1. 列出成績大於等於80的學生信息:
①select student.id,student.name,student.sex,achievement.result from student,achievement where student.id=achievement.id and achievement.result >= 80;
② select student.id,name,sex,result from student join achievement on student.id=achievement.id and result >= 80;
(注:內鏈接強制要求兩個表必須存在公共列,帶來便利性的同時也帶來了不靈活。內鏈接能夠自行指定鏈接列和鏈接條件。)
2. 列出成績最好的學生姓名:
select name,max(result) from student left join achievement on student.id=achievement.id;