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

简介:
/*
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_ID CASE  user_type  WHEN   ' a '   THEN  ta.name  WHEN   ' b '   THEN  tb.name  END AS  输出
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,如需转载请自行联系原作者


相关文章
|
1月前
|
SQL
sql语句加正则 简化查询
sql语句加正则 简化查询
16 0
sql语句加正则 简化查询
|
2月前
|
SQL
sql server链接查询
sql server链接查询
18 1
|
2月前
|
SQL
sql server简单查询
sql server简单查询
15 1
|
1月前
|
SQL 关系型数据库 MySQL
mysql一条sql查询出多个统计结果
mysql一条sql查询出多个统计结果
16 0
|
2月前
|
SQL
sql高级查询
sql高级查询
15 0
|
2月前
|
SQL 存储 数据可视化
10个高级的 SQL 查询技巧
10个高级的 SQL 查询技巧
|
3天前
|
SQL 前端开发
基于jeecgboot复杂sql查询的列表自定义列实现
基于jeecgboot复杂sql查询的列表自定义列实现
|
6天前
|
SQL 数据库
SQL数据库基础语法-查询语句
SQL数据库基础语法-查询语句
|
7天前
T-sql 高级查询( 5*函数 联接 分组 子查询)
T-sql 高级查询( 5*函数 联接 分组 子查询)
|
7天前
|
机器学习/深度学习
T-sql 各种查询命令
T-sql 各种查询命令