简体   繁体   English

从发布日期开始对mysql中的项目进行分组

[英]Grouping items from mysql by the day they were posted

So, I'm having a problem building a feed-style list of posts efficiently using PHP and Mysql. 因此,我在使用PHP和Mysql有效地构建帖子的供稿样式列表时遇到了问题。 I want to output the posts organized and grouped by the day they were posted, showing the date as a header. 我想输出按发布日期分类和分组的帖子,并将日期显示为标题。 For example: 例如:

February 9th -----------

Posts that were posted on Feb 9th

Feb 8th -----------------

Posts that were posted on the 8th

Hopefully that is clear. 希望这很清楚。 I'll try to clear up things if someone is confused. 如果有人感到困惑,我会尝试清理。

The tag in the question hints at using "GROUP BY". 问题中的标记提示使用“ GROUP BY”。 You do not need the SQL GROUP BY construct. 并不需要在SQL GROUP BY结构。 Instead, the query should look something like : 相反,查询应类似于:

SELECT *
FROM MyPostsTable
--WHERE  some optional condition
ORDER BY PostingDate -- DESC  (if you want the newer dates first)

Then as you iterate through the resuults list, in PHP, you simply need to keep tabs of the date of the items currently being output, and emit a header of sort ("February 9th ----------"), at the start of a new date. 然后,当您遍历结果列表时,在PHP中,您只需要保留当前输出项目的日期的标签,并发出一个标题(“ 2月9日----------”) ,在新日期的开始。

Edit : see Matt Bridges' answer for a sample implementation of the logic described above. 编辑 :有关上述逻辑的示例实现,请参见Matt Bridges的答案。

$sql = "SELECT PostDataColumn1, PostDataColumn2, date_format('%Y-%m-%d', DateColumn) FROM posts_table ORDER BY DateColumn DESC";
$result = mysql_query($sql);
$curDate = "";    

while (list($col1, $col2, $date) = mysql_fetch_row($result))
{
  if ($date != $curDate)
  {
    echo "$date --------\n";
    $curDate = $date;
  }

  echo "Post data: $col1 $col2";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM