2010-12-17 120 views
0

我想顯示包含評論數量和最後評論日期的項目,每個項目。SQL:選擇包含評論數量和最新評論日期的項目

SELECT item.*, 
    count(comments.itemid) AS commentcount, 
    comments.created AS commentcreated 
FROM table_items AS item 
LEFT JOIN table_comments AS comments ON (comments.itemid = item.id) 
WHERE item.published=1 
GROUP BY item.id 
ORDER BY item.created DESC 

現在commentcreated值是第一個評論的日期:我想要最後一條評論。排序依據在LEFT JOIN上不起作用。這如何實現?

回答

2

嘗試

SELECT item.*, 
    count(comments.itemid) AS commentcount, 
    max(comments.created) AS commentcreated 
FROM table_items AS item 
LEFT JOIN table_comments AS comments ON (comments.itemid = item.id) 
WHERE item.published=1 
GROUP BY item.id 
ORDER BY item.created DESC 

你需要告訴MySQL與MAX(),MIN()或其他聚合函數使用哪一個組中的日期。

+0

是的,非常感謝!這工作!但是如果我想選擇最新評論的標題呢? – Bert 2010-12-17 14:40:46

+0

我認爲這是一個不同的問題。 – Jaydee 2010-12-17 15:19:25