所以,我在使用PHP和Mysql高效地构建一个feed类型的帖子列表时遇到了问题。 我想输出按发布日期组织和分组的帖子,将日期显示为标题。例如:
February 9th -----------
Posts that were posted on Feb 9th
Feb 8th -----------------
Posts that were posted on the 8th
希望这很清楚。如果有人感到困惑,我会尽力清理事情。
答案 0 :(得分:2)
问题中的标签提示使用“GROUP BY”。您不需要SQL GROUP BY构造。相反,查询应该类似于:
SELECT *
FROM MyPostsTable
--WHERE some optional condition
ORDER BY PostingDate -- DESC (if you want the newer dates first)
然后当您在PHP中遍历resuults列表时,您只需要保留当前输出项目的日期标签,并发出排序标题(“2月9日--------- - “),在新的日期开始。
编辑:请参阅Matt Bridges对上述逻辑示例实现的回答。
答案 1 :(得分:2)
$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";
}