首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么在select之后接上一个列

2012-03-05 
如何在select之后接上一个列有个总表table_listid_start id_endC101C201对应id的名称却在另外两个表中tabl

如何在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 table1union allselect * 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_listgocreate table table_list( id_start varchar(10), id_end varchar(10))goinsert into table_list select 'C101','C201'goif object_id('table1') is not null   drop table table1gocreate table table1( id varchar(10), name varchar(10) )goinsert into table1 select 'C101','李华'goif object_id('table2') is not null   drop table table2gocreate table table2( id varchar(10), name varchar(10) )goinsert into table2 select 'C201','陈明'goselect *,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 ALLSELECT 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

热点排行
Bad Request.