如何连接六个表并从sql中的六个表中获取数据?

时间:2015-02-19 13:29:36

标签: sql-server join

我有6个表,我想要访问数据。并将其显示在一个表中。表是

T1

name|date     |item       |remarks|size
abc |18-2-2015|25mm series|done   |25
xyz |17-2-2015|25mm series|done   |30

T2

name|date     |item       |remarks|size
abc |14-2-2015|30mm series|done   |25
xyz |16-2-2015|30mm series|done   |30

T3

name|date     |item       |remarks|size
abc |11-2-2015|35mm series|done   |25
xyz |13-2-2015|35mm series|done   |30

T4

name|date     |item       |remarks|size
abc |10-2-2015|40mm series|done   |25
abc |15-2-2015|40mm series|done   |30
xyz |16-2-2015|40mm series|done   |30

T5

name|date     |item       |remarks|size
abc |6-2-2015 |45mm series|done   |25
abc |5-2-2015 |45mm series|done   |30
xyz |6-2-2015 |45mm series|done   |30

T6

name|date     |item       |remarks|size
abc |6-2-2015 |50mm series|done   |25
abc |5-2-2015 |50mm series|done   |30
xyz |6-2-2015 |50mm series|done   |30

这些是包含数据的表格,我想要结果,如果我给出的名称是abc我想要显示与该名称相关的所有6个表格数据。输出结果

输出

name|date     |item       |remarks
abc |6-2-2015 |50mm series|done   
abc |5-2-2015 |50mm series|done   
abc |6-2-2015 |50mm series|done   
abc |5-2-2015 |50mm series|done   
abc |6-2-2015 |45mm series|done   
abc |5-2-2015 |45mm series|done   
abc |10-2-2015|40mm series|done   
abc |15-2-2015|40mm series|done   
abc |11-2-2015|35mm series|done  
abc |14-2-2015|30mm series|done   
abc |18-2-2015|25mm series|done   

我试过这个查询但是得到了空

select t1.Name,t1.Date,t1.Item,t1.Remarks
from t1 p1
inner join t2 on t1.Name=t2.Name
inner join t3 on t1.Name=t3.Name
inner join t4 on t1.Name=p4.Name
inner join t4 on t1.Name=p5.Name
inner join t5 on t1.Name=p6.Name
inner join t6  on t1.Name=p2.Name
where t1.CheckListName='abc'

2 个答案:

答案 0 :(得分:0)

联盟将从所有表中选择与返回相同行的贫困行。尝试,

select Name, Date, Item, Remarks
from t1 where name = 'abc'

UNION 

select Name, Date, Item, Remarks
from t2 where name = 'abc'

UNION 

select Name, Date, Item, Remarks
from t3 where name = 'abc'

UNION 

select Name, Date, Item, Remarks
from t4 where name = 'abc'

UNION 

select Name, Date, Item, Remarks
from t5 where name = 'abc'    
UNION 

select Name, Date, Item, Remarks
from t6 where name = 'abc'

答案 1 :(得分:0)

试试这个

SELECT * FROM (
        SELECT * FROM t1
        UNION ALL
        SELECT * FROM t2
        UNION ALL
        SELECT * FROM t3
        UNION ALL
        SELECT * FROM t4
        UNION ALL
        SELECT * FROM t5
        UNION ALL
        SELECT * FROM t6
               ) AS Total
WHERE NAME = 'abc'

我认为你不应该有任何错误。