tags:

views:

248

answers:

4

Hi guys, I'm running a sql query to get basic details from a number of tables. Sorted by the last update date field. Its terribly tricky and I'm thinking if there is an alternate to using the UNION clause instead...I'm working in PHP MYSQL.

Actually I have a few tables containing news, articles, photos, events etc and need to collect all of them in one query to show a simple - whats newly added on the website kind of thing.

+1  A: 

Maybe do it in PHP rather than MySQL - if you want the latest n items, then fetch the latest n of each of your news items, articles, photos and events, and sort in PHP (you'll need the last n of each obviously, and you'll then trim the dataset in PHP). This is probably easier than combining those with UNION given they're likely to have lots of data items which are different.

I'm not aware of an alternative to UNION that does what you want, and hopefully those fetches won't be too expensive. It would definitely be wise to profile this though.

Dominic Rodger
The thing is that I need to page all the results - so basically you can have 0-n updates in any table - the idea is to make it seemless in the sense that only those entries that have been updated are collected and displayed. Kinda like facebook... HOw does facebook do it btw?!?!?
Ali
Facebook certainly caches the crazy out of it, and probably stores some kind of update table. Sadly, I'm not privy to Facebook's source code.
Dominic Rodger
+1  A: 

If you use Join in your query you can select datas from differents tables who are related with foreign keys.

bAN
A: 

There is nothing wrong with performing a UNION (unless you are really talking about joining on releated entities (i.e. those having Foreign Key relationships).

BUT you might want to use a UNION ALL rather than just UNION, as UNION will perform a sort to remove duplicate entries.

Mitch Wheat
A: 

You can look of this from another angle: do you need absolutely updated information? (the moment someone enters new information it should appear)

If not, you can have a table holding the results of the query in the format you need (serving as cache), and update this table every 5 minutes or so. Then your query problem becomes trivial, as you can have the updates run as several updates in the background.

David Rabinowitz
Nice idea - so you mean I should set up the update as a crontab job or so?
Ali