日期:2014-05-19  浏览次数:20643 次

一个表中的id字段依赖着另外两个表,如何写SQL语句?
例子如下:
有三个表Log,User,Vip
Log
id   Type
1     0
1     1
2     0
3     1
3     0

User
id   Name
1     aaa
2     bbb
3     ccc

Vip
id   Name
1     eee
2     fff
3     ddd

当Log.Type=0时,Log.id对应User.id
当Log.Type=1时,Log.id对应Vip.id

现在想把Log中id相应的Name查询出来
Name
aaa
eee
bbb
ddd
ccc

SQL语句如何写?

------解决方案--------------------
create table Log(id int,type int)
create table [User](id int,name varchar(10))
create table Vip(id int,name varchar(10))

insert into Log
select 1,0
union select 1,1
union select 2,0
union select 3,1
union select 3,0

insert into [User]
select 1, 'aaa '
union select 2, 'bbb '
union select 3, 'ccc '

insert into Vip
select 1, 'eee '
union select 2, 'fff '
union select 3, 'ddd '

select case when type=0 then [User].name else Vip.name end as name
from Log
left join [User] on [User].id=Log.id
left join Vip on Vip.id=Log.id
------解决方案--------------------
declare @Log table(id int,Type varchar(10))
insert @Log select 1, '0 '
insert @Log select 1, '1 '
insert @Log select 2, '0 '
insert @Log select 3, '1 '
insert @Log select 3, '0 '

declare @User table(id int,Name varchar(10))
insert @User select 1, 'aaa '
insert @User select 2, 'bbb '
insert @User select 3, 'ccc '

declare @Vip table(id int,Name varchar(10))
insert @Vip select 1, 'eee '
insert @Vip select 2, 'fff '
insert @Vip select 3, 'ddd '

select a.*,isnull(b.name,c.name) Name from @Log a
left join @User b on a.type=0 and a.id=b.id
left join @Vip c on a.type=1 and a.id=c.id

--结果
id Type Name
----------- ---------- ----------
1 0 aaa
1 1 eee
2 0 bbb
3 1 ddd
3 0 ccc

(所影响的行数为 5 行)
------解决方案--------------------
declare @Log table([id] int,Type int)
insert into @Log
select 1,0
union select 1,1
union select 2,0
union select 3,1
union select 3,0

declare @User table(id int,Name varchar(3))
insert into @user
select 1, 'aaa '
union select 2, 'bbb '
union select 3, 'ccc '

declare @Vip table(id int,Name varchar(3))
insert into @vip
select 1, 'eee '
union select 2, 'fff '
union select 3, 'ddd '

select * from @log
select * from @user
select * from @vip


select l.id,case type when 1 then v.name else u.name end as name
from @log l,@user u,@vip v
where l.id=u.id and l.id=v.id
------解决方案--------------------
select log.id,log.type, vip.name from log left join user on log.type=0 and log.id=user.id left join vip on log.type=1 and log.type=vip.id
------解决方案--------------------
除了ShiningG()的,樓上的都對