--每种宠物各有几只
select species,count(*) from pet group by species
--查询年龄最大的宠物的信息
select * from pet where birth =
(select max(birth) from pet)
--每年各出生了几只宠物
select year(birth), count(*) from pet group by year(birth)
--鸟和猫的性别比例
select species, sex, count(*)
from pet
where species in ('cat','bird')
group by species, sex
--各种宠物年龄的和
select species, sum(truncate(datediff(now(),birth)/365,0)) as SumAge
from pet
group by species
--数量大于1的宠物种类
select species, count(*) as c
from pet
group by species
having c>=2
--基本双表关联
select a.name,a.species, a.sex,b.date, b.type, b.remark
from pet a,event b
where a.name = b.name
--查询宠物产仔时的年龄
select a.name, a.species,
truncate(datediff(b.date,a.birth)/365,0) as age
from pet a,event b
where a.name = b.name and b.type='litter'
--90年代出生的狗的事件列表
select a.name,birth,species,sex,date,type,remark
from pet a,event b
where a.name=b.name and birth between '1990' and '1999'
and species='dog'
--活着的宠物按发生的事件类型分组,看各种事件发生的次数
select type, count(*)
from pet a, event b
where a.name=b.name and a.death is null
group by type
--记录的事件数量超过1条的宠物信息
select a.name,species,sex,count(*)
from pet a, event b
where a.name = b.name
group by b.name
having count(*)>=2
--列出发生了两件事情的宠物的事件记录信息
select a.name,type,date,remark,b.species,b.sex,b.owner
from event a, pet b
where a.name=b.name and
b.name in
(
select name
from event
group by name
having count(*)=2
)
--插入语句
insert into pet (name,species,birth)
values ('KKK','snake','2007-01-01');
insert into pet
values ('KK','Diane','cat','f',null,null);
insert into pet set name='k',owner='Benny'
--更新语句
update pet set species='snake',sex='f',birth=now()
where name='k'
--将事件表中生日的日期,更新到pet表中相应宠物的birth字段
update pet a
set birth = (
select date
from event b
where a.name=b.name and b.type='birthday'
)
where a.name in (
select name
from event
where type='birthday'
)
--删除语句
delete from pet where name like 'k%'