SQL:选择包含注释数和最新注释日期的项目

时间:2010-12-17 14:11:51

标签: mysql left-join

我想显示包含评论数量和最后评论日期的项目,每个项目。

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

现在,评论创建的值是第一条评论的日期:我想要最后一条评论。订单在LEFT JOIN上不起作用。如何实现这一目标?

1 个答案:

答案 0 :(得分: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()或其他聚合函数一起使用。