I have three tables of data:
table: cars [10,000 rows]
table: planes [2,000 rows]
table: trains [50 rows]
I’d like to be able to show users a page of data taken from the three tables like:
car
plane
train
car
plane
train
...
The point being that they can keep paging, seeing one of each type, until each table is exhausted. For example, at some point, each page would only contain cars as the plane and train tables will be exhausted way before the cars table is.
Is there a query I can run to grab one row from each table, until a limit is reached? Something like:
SELECT * FROM cars, planes, trains ORDER BY (natural row ordering?) LIMIT 20;
The only way I can think to get this done is to make one master table, and assign a dummy integer to each row as I insert them:
id | type | description | dummy_integer
--------------------------------------------
... car ... 0
... plane ... 1
... train ... 2
... car ... 3
... plane ... 4
... train ... 5
... ... ... ...
... car ... 8000
... car ... 8001
... car ... 8002
... ... ... ...
Then I can do:
SELECT * FROM master_table ORDER BY dummy_integer ASC LIMIT 20;
and paging is done by using the last-seen dummy_integer:
SELECT * FROM master_table WHERE dummy_integer > 20
ORDER BY dummy_integer ASC LIMIT 20;
Then the problem becomes that when I get some new train records for example, I can append them to the end of master_table, but their dummy integer values would put them all the way at the end. Therefore if a user starts looking at my pages from the start, they won’t see that newer train data until they page through the cars desert, instead of nicely interleaved with the cars/planes up towards the front.
Is there any good way of doing this besides the above (not so great) way?
Thanks
Aren’t the commas on your query actually performing a join?
I’d use an
UNIONandORDER BYto achieve that:(working example)
For pagination, you can use
LIMITwithOFFSET(see docs).