父表:father
fid fname
1 a
2 b
3 c
4 e
insert into father values(1,'a');
insert into father values(2,'b');
insert into father values(3,'c');
insert into father values(4,'e');
create table father(
fid int primary key,
fname varchar(10)
);
一对多:父子表,主从(明细)表,
sid sname fid height money
insert into son values(100,'s1',1,1.7,8000);
insert into son values(101,'s2',2,1.6,7500);
insert into son values(102,'s3',2,1.8,8000);
create table son(
sid int primary key,
sname varchar(8),
fid int,
height decimal(10,2),
money decimal(16,2)
);
1、查询sid、sname、fid
2、查询各儿子涨价20%以后的新学费,注意,8000块以下的不涨价。
要求同时显示所有涨价和没有涨价的学费。
3、sid、sname、fid、fname
4、fid、fname、儿子数(没有儿子的不显示)
5、fid、fname、儿子数(没有儿子的个数显示为0)
也可以用相关子查询,但是效率低,所以尽量不要用。
6、找出不止有1个儿子的father信息:fid、fname、儿子数 两种:
7、找出儿子最多的father信息:fid、fname、儿子数
8、找出fid为(1,2,4)的father中,各儿子的身高
9、找出各father中身高最高的儿子。
10、找出身高在1.8到1.65之间的所有儿子及父亲信息:fid,fname,sid,sname,height
答案:
2题
select sname,money,money*1.2 as new_money,'涨价' as flag
from son where money>=8000
union all
select sname,money,null,'不涨'
from son where money<8000;
4题:
select f.fid,f.fname,count(*) x
from father f join son s on f.fid=s.fid
group by f.fid,f.fname
5题:
select f.fid,f.fname,count(s.sid) x
from father f left join son s on f.fid=s.fid
group by f.fid,f.fname
6题:
select f.fid,f.fname,count(*) x
from father f join son s on f.fid=s.fid
group by f.fid,f.fname
select f.fid,f.fname,count(*) x
from father f join son s on f.fid=s.fid
group by f.fid,f.fname
having count(*)>1
select * from (
select f.fid,f.fname,count(*) x
from father f join son s on f.fid=s.fid
group by f.fid,f.fname
) t
where x>1;
7题:
select f.fid,f.fname,count(*) x
from father f join son s on f.fid=s.fid
group by f.fid,f.fname
having count(*)=(
select max(count(*)) from son group by fid
);
select f.fid,f.fname,count(*) x
from father f join son s on f.fid=s.fid
group by f.fid,f.fname
having count(*)=(
select max(rs) from (select count(*) rs from son group by fid) t
);