根据不同的条件查询不同的表 sql

本文通过具体的SQL案例,展示了如何使用Case语句根据不同的条件从多个表中选择相应的记录。示例包括了创建和填充三个表的过程,并提供了两种方法来实现基于c表中的user_type字段来选择显示a表或b表中的name字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
a表 a.user_id  a.name 
b表 b.user_id  b.name 
c表 c.user_id  c.user_type 

当c表的 c.user_type = "a" 时 它显示 a表的 a.name 
当c表的 c.user_type = "b" 时 它显示 b表的 b.name 
a,b,c表中的 a.user_id = c.user_id,b.user_id = c.user_id 

*/

if object_id('ta')is not null drop table ta
go
create TABLE ta([user_ID] int,name varchar(50))
INSERT INTO ta select
1,'a1' union all select
2,'a2'

if object_id('tb')is not null drop table tb
go
create TABLE tb([user_ID] int,name varchar(50))
INSERT INTO tb select
1,'b1' union all select
2,'b2'

if object_id('tc')is not null drop table tc
go
create TABLE tc([user_ID] int,user_type varchar(50))
INSERT INTO tc select
1,'a' union all select
2,'b'

select * from ta
select * from tb
select * from tc

--方法一

select c.[user_id],name=case user_type when 'a' then a.name  when 'b' then b.name end
from tc c,ta a,tb b
where a.[user_id]=c.[user_id] and b.[user_id]=c.[user_id]  

--方法二

SELECT     tc.user_IDCASE user_type WHEN 'a' THEN ta.name WHEN 'b' THEN tb.name ENDAS 输出
FROM         tc INNER JOIN
                      ta 
ON tc.user_ID = ta.user_ID INNER JOIN
                      tb 
ON tc.user_ID = tb.user_ID


/*

user_ID     name
----------- --------------------------------------------------
1           a1
2           a2


user_ID     name
----------- --------------------------------------------------
1           b1
2           b2


user_ID     user_type
----------- --------------------------------------------------
1           a
2           b


user_id     输出
----------- --------------------------------------------------
1           a1
2           b2



*/

    本文转自曾祥展博客园博客,原文链接:http://www.cnblogs.com/zengxiangzhan/archive/2009/12/05/1617458.html,如需转载请自行联系原作者



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值