日期:2014-05-18  浏览次数:20642 次

如何在select之后接上一个列

有个总表
 table_list
id_start id_end
C101 C201

对应id的名称却在另外两个表中

 table1
id name
C101 李华

 table2
id name
C202 陈明


我要查询table_list.但是却不能通过id得到名称。

我想在后面加上两个列,放对应的名字,但是不知道怎么写。
或者有其他方法?

------解决方案--------------------
SQL code
select * from(
select * from table1
union all
select * from table2
)t where id between (select id_start from table_list) and (select id_end) from table_list)

------解决方案--------------------
SQL code

if object_id('table_list') is not null
   drop table table_list
go
create table table_list
(
 id_start varchar(10),
 id_end varchar(10)
)
go
insert into table_list select 'C101','C201'
go
if object_id('table1') is not null
   drop table table1
go
create table table1
(
 id varchar(10),
 name varchar(10)
 )
go
insert into table1 select 'C101','李华'
go
if object_id('table2') is not null
   drop table table2
go
create table table2
(
 id varchar(10),
 name varchar(10) 
)
go
insert into table2 select 'C201','陈明'
go
select *,name1=(select name from table1 where id=a.id_start),name2=(select name from table2 where id=a.id_end) from table_list a
/*
id_start   id_end     name1      name2
---------- ---------- ---------- ----------
C101       C201       李华         陈明

(1 行受影响)

*/

------解决方案--------------------
SQL code
SELECT T1.* FROM TABLE1 T1 
WHERE EXISTS(SELECT 1 FROM table_list WHERE T1.ID BETWEEN id_start AND id_END)
UNION ALL
SELECT T1.* FROM TABLE2 T1 
WHERE EXISTS(SELECT 1 FROM table_list WHERE T1.ID BETWEEN id_start AND id_END)

------解决方案--------------------
/*
有个总表
table_list
id_start id_end
C101 C201
对应id的名称却在另外两个表中
table1
 id name
 C101 李华

table2
 id name
 C202 陈明
我要查询table_list.但是却不能通过id得到名称。
*/

go
if OBJECT_ID('table_list')is not null
drop table table_list
go
create table table_list(
id_start char(5),
id_end char(5)
)
insert table_list
select 'C101','C102'
go
if OBJECT_ID('table1')is not null
drop table table1
go
create table table1(
id char(5),
name char(8)
)
go
insert table1
select 'C101','李华'

go
if OBJECT_ID('table2')is not null
drop table table2
go
create table table2(
id char(5),
name char(8)
)
go
insert table2
select 'C102','陈明'
----你的意思是?
select *from (
select *from table1
union all
select *from table2
) as tbl where id=(select id_start from table_list )
or id=(select id_end from table_list)
------------------------------------------------------
select *,
name1=(select name from table1 where id=a.id_start),
name2=(select name from table2 where id=a.id_end) 
from table_list a