I have 2 tables that i have to get last 10 active project ids from based on the date. The query is:
(
SELECT project_posts.projectid as projectId, `project_posts`.`date` as rowDate
FROM `project_posts` ORDER BY `project_posts`.id DESC
)
UNION ALL
(SELECT `project_comments`.projectid as projectId, project_comments.`date` as rowDate FROM `project_comments` ORDER BY `project_comments`.id DESC) GROUP BY projectId ORDER BY rowDate DESC LIMIT 10
And i want to sort it by rowDate DESC (last project first). The problem is that when i add group by MySQL says:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY projectId ORDER BY rowDate DESC LIMIT 6' at line 9
I looked over the internet for problems with union, union all and group by, but I didn’t find any solution.
Thanks in advance.
I think you need to create a derived table from your union query before you can group on it –
I have not had a chance to try this but it should do what you are after –
UPDATE The UNION based query should be significantly faster than this second query. I have done some crude tests using some dummy data (100k projects, 200k posts and 700k comments) and the multi join query takes three to five times longer than the UNION query.