日期:2014-05-18 浏览次数:20695 次
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)
------解决方案--------------------
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 行受影响) */
------解决方案--------------------
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