MySQL group by union#1064错误

时间:2012-03-01 20:41:31

标签: mysql database syntax-error

我有2个表,我必须根据日期获取最后10个活动项目ID。查询是:

(
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

我想通过rowDate DESC(最后一个项目)排序。问题是当我通过My​​SQL添加组时说:

#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

我查看了互联网上有关工会,工会全部和分组的问题,但我没有找到任何解决方案。 提前谢谢。

1 个答案:

答案 0 :(得分:5)

我认为您需要先从联合查询中创建派生表,然后才能对其进行分组 -

SELECT projectId, MAX(rowDate) AS rowDate
FROM (
    (
        SELECT project_posts.projectid as projectId, `project_posts`.`date` as rowDate 
        FROM `project_posts`
    ) UNION ALL (
        SELECT `project_comments`.projectid as projectId, project_comments.`date` as rowDate
        FROM `project_comments`
    )
) AS tmp
GROUP BY projectId
ORDER BY rowDate DESC
LIMIT 10

我没有机会尝试这个,但它应该做你想做的事 -

SELECT p.id, GREATEST(IFNULL(MAX(pc.date), 0), IFNULL(MAX(pp.date), 0)) AS max_date
FROM projects p
LEFT JOIN project_comments pc
    ON p.id = pc.projectid
LEFT JOIN project_posts pp
    ON p.id = pp.projectid
GROUP BY p.id
ORDER BY max_date DESC
LIMIT 10

UPDATE 基于UNION的查询应该明显快于第二个查询。我使用一些虚拟数据(100k项目,200k帖子和700k注释)进行了一些原始测试,多连接查询比UNION查询长三到五倍。