2012-03-01 111 views
0

我有2個表格,我必須從日期得到最後10個活動項目ID。查詢是:MySQL group by after union#1064 error

(
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(最後項目第一)對它排序。問題是,當我被MySQL添加組說:

 
#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 

我看着在互聯網上與工會,工會都和group by的問題,但我沒有找到任何解決方案。 在此先感謝。

回答

4

我認爲你需要,才能在IT團隊從聯合查詢創建派生表 - 我還沒有機會後,試試這個,但它應該做的你是什麼

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基於查詢應該比這個第二查詢顯著快。我已經使用一些虛擬數據(10萬個項目,20萬個帖子和700萬條評論)做了一些粗略的測試,並且多聯接查詢比UNION查詢長3到5倍。

+0

非常感謝您的快速回復。現在查詢運行,但排序不正確,我沒有拿到最後的項目ID(當我爲日期DESC排序的兩個塔布運行單獨的select時,它們是不同的)。我嘗試用ORDER BY'project_comments'.'date' DESC和'project_posts'.'date' DESC來更改每個select(在UNION中)的ORDER BY子句,但它仍然存在。任何建議?提前致謝。 – some12die4 2012-03-01 21:04:00

+0

我剛剛閱讀您的原始文章。到底什麼是最終目標和什麼是表結構?我不認爲用UNION進行查詢是最好的方法。 – nnichols 2012-03-01 21:26:50

+0

對不起,誤會。我想根據他們的活動(帖子和評論)獲取最近10個活動項目。我沒有找到與工會不同的方式。 – some12die4 2012-03-01 21:40:10