很有挑战的SQL题目,想挑战吗?

来源:百度知道 编辑:UC知道 时间:2024/07/07 20:41:36
create table a
(
aid int primary key identity(1,1),
aname varchar(20),
apwd varchar(20),
age int
)
go
create table b
(
bid int primary key identity(1,1),
baid int foreign key references a(aid),
bdate datetime
)
create table c
(
cid int primary key identity(1,1),
caid int foreign key references a(aid),
cbid int foreign key references b(bid),
cdate datetime
)
insert into a values('张三','zs',22)
insert into a values('李四','ls',18)
insert into a values('王五','wu',28)
go
insert into b values(1,getDate())
insert into b values(2,getDate())
insert into b values(3,getDate())
go
insert into c values(1,3,getDate())
insert into c values(1,2,getDate())
insert into c values(1,1,getDate())
go
select * from c
select * from b
select * from a
go

--提问:根据表c的cbid查

select * from a,b,c where b.bid=c.cbid and b.baid=a.aid

就是根据主外键将a和b表连接起来,然后通过b和c表的主外键连接起来就可以
把a,b,c 表连接起来了呀,查所有的数据。

select * from c
join b on b.bid=c.bid
join a on a.aid=c.aid

select a.*,b.* from a,b,c where b.baid=c.cbid and b.baid=a.aid

Select * from a, b, c
Where a.aid = b.baid And a.aid = c.caid And b.bid = c.cbid