2012-06-19 59 views
3

我有三個數據表:通過三個數據表進行分頁?

table: cars [10,000 rows] 
table: planes [2,000 rows] 
table: trains [50 rows] 

我希望能夠向用戶展示來自三個表等拍攝數據頁:

car 
plane 
train 
car 
plane 
train 
... 

的一點是,它們能保持分頁,看每種類型,直到每張表被耗盡。例如,在某些時候,每個頁面將只包含汽車作爲飛機和火車表將車表是用盡後再方式。

有一個查詢我可以運行在每個表搶一行,直到達到極限?喜歡的東西:

SELECT * FROM cars, planes, trains ORDER BY (natural row ordering?) LIMIT 20; 

我能想到得到這個工作的唯一方法是使一個主表,並分配到各行的虛擬整數,我將它們插入:

id | type | description | dummy_integer 
-------------------------------------------- 
... car  ...    0 
... plane ...    1 
... train ...    2 
... car  ...    3 
... plane ...    4 
... train ...    5 
... ...  ...    ... 
... car  ...    8000 
... car  ...    8001 
... car  ...    8002 
... ...  ...    ... 

那麼我就可以這樣做:

SELECT * FROM master_table ORDER BY dummy_integer ASC LIMIT 20; 

和尋呼被利用上一次看到dummy_integer完成:

SELECT * FROM master_table WHERE dummy_integer > 20 
    ORDER BY dummy_integer ASC LIMIT 20; 

那麼問題就變成,當我得到例如一些新的列車運行記錄,我可以追加他們master_table結束,但他們的虛擬整數值將使他們在最後一路。因此,如果用戶開始盯着從一開始我的網頁,他們將看不到新的列車數據,直到他們翻閱汽車沙漠,不是很好的交錯與汽車/飛機,邁向前方。

是否有這樣做除了上述的(沒那麼大)的方式什麼好辦法?

感謝

+0

只是在做三個獨立統一的查詢可能會比招數更快。確保你的個人資料。 –

回答

1

不在查詢實際執行加入逗號?

我會用一個UNIONORDER BY以達到:

SELECT id, type, description FROM cars 
UNION 
SELECT id, type, description FROM planes 
UNION 
SELECT id, type, description FROM trains 
ORDER BY id, type 

working example

對於分頁,可以使用LIMITOFFSET(見docs)。

+0

這正是我正在尋找的,謝謝。 – user291701

0

如果您使用的是Oracle,這會爲你工作:

select 
    1 as typer, 
    a.id, 
    a.type, 
    a.description, 
    row_number() over (partition by typer order by typer) as ranker 
from 
    cars a 
union 
select 
    1 as typer, 
    a.id, 
    a.type, 
    a.description, 
    row_number() over (partition by typer order by typer) as ranker 
from 
    planes a 
union 
select 
    1 as typer, 
    a.id, 
    a.type, 
    a.description, 
    row_number() over (partition by typer order by typer) as ranker 
from 
    trains a 
order by 
    ranker asc; 

我沒有改變你的列名,但使用的是一些保留的話,可能不是最好的。

相關問題