views:

270

answers:

4

Hello, I'm creating a page where I want to make a history page. So I was wondering if there is any way to fetch all rows from multiple tables and then sort by their time? Every table has a field called "created_at".

So is there any way to fetch from all tables and sort without having Rails sorting them form me?

A: 

Use Order By in your SQL. So your query might look like this

Select * from table order by created_at
Jonathan
I know how to sort when using a single table, but how can I sort when fetching from multiple tables?
Terw
(SELECT a FROM t1 WHERE a=10 AND B=1)UNION(SELECT a FROM t2 WHERE a=11 AND B=2)ORDER BY a LIMIT 10;
Kamil Szot
A: 

Depending on whether these databases are all on the same machine or not:

On same machine: Use OrderBy and UNION statements in your sql to return your result set

On different machines: You'll want to test this for performance, but you could use Linked Servers and UNION, ORDER BY. Alternatively, you could have ruby get the results from each db, and then combine them and sort

EDIT: From your last comment about different tables and not DB's; use something like this:

SELECT Created FROM table1
UNION
SELECT Created FROM table2
ORDER BY created
Jim B
A: 

You would need to perform the sql like:

Select * from table order by created_at incr

: Store this into an array. Do this for each of the data sources, and then perform a merge sort on all the arrays in Ruby. Of course this will work well for small data sets, but once you get a data set that is large (ie: greater than will fit into memory) then you will have to use a different collect/merge algorithm.

So I guess the answer is that you do need to perform some sort of Ruby, unless you resort to the Union method described in another answer.

Zubair
+1  A: 

You may get a better answer, but I would presume you would need to

  1. Create a History table with a Created date column, an autogenerated Id column, and any other contents you would like to expose [eg Name, Description]
  2. Modify all tables that generate a "history" item to consume this new table via Foreign Key relationship on History.Id

"Mashing up" tables [ie merging different result sets into a single result set] is a very difficult problem, but you would effectively be doing the above anyway - just in the application layer, so why not do it correctly and more efficiently in the data layer.

Hope this helps :)

johnny g
Was hoping to not having to use it this way ;) But was this way I thought was the easiest and fastest.
Terw
Why would you go through all the effort of making new tables when you can use UNION?
Jim B