0

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

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

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

4

2 回答 2

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 ....)
)
于 2012-08-09T04:27:24.853 回答
0

一些数据库不允许您在联合查询中提供“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')
)
于 2012-08-09T04:53:53.583 回答