日期:2014-05-19  浏览次数:20482 次

一个数据检索的问题
现在有种情况,一个表中,一个字段对应两个主表,也就是说一个字段中的数据有两种,现在想把所有的数据都检索出来,有没有什么好办法吗?
例如:
Table1    
                              code         companycode                       b      
以前的数据             1                   1(联想)                       ..
                                2                   2(IBM)                           ..
新的数据        
                                3               10001(联想)                     ..  
                                4               10002(IBM)                       ..

现在想一起把他们检索并显示出来,有什么好办法吗?
谢谢各位高手

------解决方案--------------------
用union all合并表后进行检索
------解决方案--------------------

--合并重复行
select * from A
union
select * from B


--不合并重复行
select * from A
union all
select * from B
------解决方案--------------------

create table T1(ID int, code int, name varchar(10), companycode varchar(10))
insert T1 select 1, 1, '张三 ', '1 '
union all select 2, 2, '李四 ', '2 '
union all select 3, 1, '张三 ', '10001 '
union all select 4, 2, '李四 ', '10002 '
go
create table T2(companycode int, companyname varchar(10))
insert T2 select 1, '联想 '
union all select 2, 'IBM '
go
create table T3(companycode varchar(10), companyname varchar(10))
insert T3 select '10001 ', '联想 '
union all select '10002 ', 'IBM '

select T1.ID, T1.code, T1.name,
companyname=isnull(T2.companyname, T3.companyname)
from T1
left join T2 on T1.companycode=T2.companycode
left join T3 on T1.companycode=T3.companycode

--result
ID code name companyname
----------- ----------- ---------- -----------
1 1 张三 联想
2 2 李四 IBM
3 1 张三 联想
4 2 李四 IBM

(4 row(s) affected)