组合select语句获得的结果集来创建视图

时间:2012-08-09 04:24:06

标签: sql union union-all

我有4个不同表的4个Select语句 每个Select查询给出最新记录满足指定条件 例如:

Select TOP 1 * from table where column_name = 'something' order by col1 DESC;

现在我必须组合所有4个查询的结果集,并从组合结果集中创建一个视图。

2 个答案:

答案 0 :(得分:4)

create view some_view as
(
(select TOP 1 * from table1 where ....)
UNION ALL
(select TOP 1 * from table2 where ....)
UNION ALL
(select TOP 1 * from table3 where ....)
UNION ALL
(select TOP 1 * from table4 where ....)
)

答案 1 :(得分:0)

某些DB不允许您在联合查询中提供“order by”子句。

如果您按col1 desc订购,可能是某种类型的列可以应用min()或max()。

如果是这种情况,下面可以解决您的问题(如果没有太多记录,或者,如果表格很大,“col1”和“some_column”将被编入索引。)

create view some_view as
(
select * from table1
  where some_column = 'something'
  and col1 = (select max(col1) from table1 where some_column = 'something')
UNION ALL
select * from table2 
  where some_column = 'something'
  and col1 = (select max(col1) from table2 where some_column = 'something')
UNION ALL
select * from table3 
  where some_column = 'something'
  and col1 = (select max(col1) from table3 where some_column = 'something')
UNION ALL
select * from table4 
  where some_column = 'something'
  and col1 = (select max(col1) from table4 where some_column = 'something')
)