how can I use Zend_Db_Select to directly select from a subquery (derived table)?
See, I have 5 tables with the same structure, I want to get all rows from them, merge them and remove the duplicates. I am using UNION which removes duplicates automaticly. The problem is that I add a static column to each table before, so there is one column which is different => duplicatation occures.
Here is my query so far:
SELECT `news_main`.*, 'main' as `category`
FROM `news_main`
UNION SELECT `news_politics`.*, 'politics' as `category` FROM `news_politics`
UNION SELECT `news_society`.*, 'society' as `category` FROM `news_society`
UNION SELECT `news_world`.*, 'world' as `category` FROM `news_world`
UNION SELECT `news_business`.*, 'business' as `category` FROM `news_business`
ORDER BY `date` DESC LIMIT 8
See how I add static values to the new column category? Now everything else is the same (there are duplicate rows), but since they are from different categories, UNION can’t remove them.
So I thought I could SELECT all rows from this sub-query and group them to remove duplicates, like this:
SELECT *
FROM (
SELECT `news_main`.*, 'main' as `category`
FROM `news_main`
UNION SELECT `news_politics`.*, 'politics' as `category` FROM `news_politics`
UNION SELECT `news_society`.*, 'society' as `category` FROM `news_society`
UNION SELECT `news_world`.*, 'world' as `category` FROM `news_world`
UNION SELECT `news_business`.*, 'business' as `category` FROM `news_business`
ORDER BY `date` DESC LIMIT 8
) as subtable
GROUP BY `source`
ORDER BY `date` DESC
I did run this in MySQL and it works perfectly.. the only problem is….
How do I execute this using Zend_Db_Select’s fancy functions?
Thanks in advance!
I’m not sure if you can use nesting selects in the from construct of Zend_Db_Select or if you should even be doing it that way, but an alternative solution would be to just get the db adapter and build the sql query manually.
related:
Zend_Db_Table subquery