SQL查询分别从三个表中选择记录

时间:2010-04-15 13:43:53

标签: sql sql-server-2005

从三个表中选择记录的SQL查询,这些表之间没有关系。其实我想把它变成一个视图。

假设有三个故事Table1, Table2, Table3

我想先用一些过滤条件显示Table1的记录 然后是Table2中的记录 从表3中可以看出,当我们执行视图时,它就像表格一样显示。

可以有任意数量的行,但记录必须按此顺序排列。

7 个答案:

答案 0 :(得分:3)

如果您想要每个表中的所有记录,我建议使用UNION ALL而不是union。 UNION将使用distinct来过滤掉重复项。如果你不需要它只会减慢查询速度。

这里有进一步的解释: http://wiki.lessthandot.com/index.php/Union_All

向您展示如何在每个表中没有所有列时进行处理:

select 
   1 as seq,col1, col2, col3, cast(null as varchar (40)) as col4 
   FROM Table1 
   where ... 
UNION ALL 
select 
   2 as seq,'Unknown', col2, null, col4 
   FROM Table2 
   where ... 
UNION ALL 
select 
   3 as seq ,col1, col2, col3, cast(null as varchar (40)) as col4  
   FROM Table3 
   where ... 
ORDER BY seq

答案 1 :(得分:2)

尝试:

select
   1,col1, col2, col3
   FROM Table1
   where ...
UNION ALL
select
   2,col1, col2, col3
   FROM Table2
   where ...
UNION ALL
select
   3,col1, col2, col3
   FROM Table3
   where ...
ORDER BY 1

请注意,三个查询中的每一个都需要具有相同的列数,并且数据类型也应该一致。此外,我使用UNION ALL来加速查询,因为没有用于消除三个查询之间的重复,因为序列表将保证没有重复。

在结果集中没有序列列,请尝试:

SELECT
    col1,col2,col3 
    FROM (select
             1 as seq,col1, col2, col3
             FROM Table1
             where ...
          UNION ALL
          select
             2 as seq,col1, col2, col3
             FROM Table2
             where ...
          UNION ALL
          select
             3 as seq,col1, col2, col3
             FROM Table3
             where ...
         ) dt
    ORDER BY seq

答案 2 :(得分:1)

您可以使用UNION查询:

SELECT Field1, Field2, Field3, '1' as Sequence FROM Table1 WHERE SomeCriteria
UNION
SELECT Field7, Field5, Field6, '2' FROM Table2 WHERE SomeCriteria
UNION
SELECT Field4, Field8, Field9, '3' FROM Table3 WHERE SomeCriteria

答案 3 :(得分:1)

怎么样:

create view AZ_VIEW as
select 1 as orderby, tbl1Col1 as col1, tbl1Col2 as col2, tbl1col3 as col3 from Table1 where criteria1='val'
union 
select 2, tbl2Col1, tbl2Col2, tbl2col3 from Table2 where criteria2='anotherval'
union 
select 3, tbl3Col1, tbl3Col2, tbl3col3 from Table3 where criteria3='athirdval'
;

答案 4 :(得分:1)

如果您的表共享相同的列,则可以使用Union All

Select col1, col2, 1 As seq
From table1
Union All
Select col1, col2, 2 As seq
From table1
Union All
Select col1, col2, 3 As seq
From table1
Order By seq

答案 5 :(得分:1)

你可以联合这三个表,注意确保它们都返回相同数量的字段。有一个简单的作弊来控制秩序(见下文):

SELECT * FROM ( 选择a,b,c,1作为ListOrder FROM table1 联盟 选择a,b,c,2作为ListOrder FROM table2 联盟 选择a,b,c,3作为ListOrder FROM table3 ) 订单按ListOrder

答案 6 :(得分:0)

你可以这样做 - WHERE ID = 34只是一个示例过滤器:

create view vAllRecords as
select 1 as Rank, Field1, Field2 from Table1 where ID  = 34
UNION
select 2 as Rank, Field1, Field2 from Table2
UNION
select 3 as Rank, Field1, Field2 from Table3

使用UNION将删除任何重复项。如果您知道没有重复项,或者您希望看到它们,则查询将以UNION ALL代码运行得更快。

视图中不允许

ORDER BY,因此当您从视图中选择时,您需要按Rank排序:

select *
from vAllRecords 
order by Rank