2012-08-09 67 views
0

我有4個4頁不同的表 Select語句中的每個SELECT查詢給定條件 爲前最新記錄會議:相結合的結果集創建一個視圖

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

現在我必須結合所有4個查詢的結果集,並從組合結果集中創建一個視圖。

+0

無論如何,你的問題是什麼?我認爲你已經回答了你的問題,並通過創建視圖來結合結果。 – 2012-08-09 04:28:08

+0

@patrickchoi:顯然他不知道*如何組合它們(即'UNION'關鍵字) – 2012-08-09 04:28:35

回答

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') 
) 
+0

感謝您的回答 – AChamp 2012-08-09 10:55:51

+0

如果它對您有用,您能接受答案嗎? ? – Hotel 2012-08-09 15:32:32

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

我不能使用UNION語句的順序 – AChamp 2012-08-09 04:33:25

+0

@AChamp只要你有一個限制條件(即'TOP 1') – 2012-08-09 04:47:54

+1

這是一個SQL小提琴示例,顯示它的工作原理...... http://sqlfiddle.com/#!3/1f7f3/1 – 2012-08-09 04:54:06