按相同条目分组注释,按日期排序

时间:2011-09-02 19:32:26

标签: php mysql comments grouping

我有一个名为comments的表,结构如下:

id | entry_id | date | comment

我还有一个名为entries的表,结构如下:

entry_id | title | date | entry

我只想展示最近添加了这些评论的评论和条目。

现在我正在使用此查询:

SELECT c.id,
       c.date,
       c.comment,
       e.entry_id,
       e.title
FROM   entries e
       INNER JOIN comments c
        ON e.entry_id = c.entry_id
GROUP  BY c.date DESC
LIMIT  50

我输出结果:

#entry_id
  1 hour ago:
  Some comment

#entry_id
  2 hours ago:
  Some comment    

评论按日期排序。我想要做的只是按同一个entry_id分组评论,例如:

#entry_id
  1 hour ago:
  Some comment

  2 hours ago:
  Some comment without  repeating the `entry_id`

#other entry_id
  5 hours ago:
  Some comment

我该怎么做?不需要为我编写代码,只需说明将如何做(例如,伪代码)。这是评论在facebook或google + stream上分组,我希望你理解我的意思。

3 个答案:

答案 0 :(得分:1)

使用此:Grouping arrays in PHP

我想我不应该写有关MySQL表结构的详细信息,用PHP和数组完成。感谢大家的关注。

$groups = array();

foreach($items as $item)
    $groups[$item['value']][] = $item;

答案 1 :(得分:0)

首先按entry_ID分组,然后按最大日期分组。你关心的是最近的一个。 (至少Facebook是这样做的。)

以下是TSQL中的代码

在内部查询中,我选择entry_id和最新评论的日期。

然后我通过最新评论或最新条目(取决于最近发生的事情)链接到该列表排序,然后通过entry_id对它们进行排序(因此所有条目评论将是第一个,最后是日期所以条目中的注释将按正确顺序排列。

注意:我没有测试此代码,因此可能会有一些拼写错误。

SELECT * FROM
  (SELECT e.entry_id, MAX(c.date) as latest
  FROM   entries e
  INNER JOIN comments c ON e.entry_id = c.entry_id
  GROUP BY e.entry_id DESC, max(c.date)
  ) AS LIST
LEFT JOIN entries e ON e.entry_id = LIST.entry_ID
LEFT JOIN comments c on c.entry_ID = LIST.entry_ID
ORDER BY MAX(e.date,list.latest) as time_of_entry_or_comment DESC,
                                    e.entry_ID, 
                                    c.date DESC

答案 2 :(得分:0)

我想你会做一个像这样的查询

select
  e.entry, e.title, c.comment, c.date
from 
  comments c join entries e on c.entry_id = e.entry_id
order by 
  e.entry_id, c.date desc

并且在entry_id仍然相同的情况下对结果集进行循环。虽然我不确定你的问题在哪里你想要输出。在代码或sql编辑器中。

相关问题