SQL按日期分组并显示每天的每个类别

时间:2013-03-26 09:27:50

标签: php mysql

我有一个名为categories的表格和一个名为posts的表格。每个帖子都有日期,标题,ID和catID。如何进行返回按日期排序的每个cateogry的第一篇文章的查询。

示例:

Post_ID 1 "Title 1"  "Cat1" "26-03.2013 13:00"
Post_ID 2 "Title 2"  "Cat1" "26-03.2013 13:05"
Post_ID 3 "Title 3"  "Cat1" "25-03.2013 13:00"
Post_ID 4 "Title 4"  "Cat1" "25-03.2013 13:05"


Post_ID 5 "Title 5"  "Cat2" "26-03.2013 14:00"
Post_ID 6 "Title 6"  "Cat2" "26-03.2013 14:05"
Post_ID 7 "Title 7"  "Cat2" "25-03.2013 14:00"
Post_ID 8 "Title 8"  "Cat2" "25-03.2013 14:05"

Post_ID 9 "Title 9"  "Cat3" "26-03.2013 15:00"
Post_ID 10 "Title 10"  "Cat3" "26-03.2013 15:05"
Post_ID 11 "Title 11"  "Cat3" "25-03.2013 15:00"
Post_ID 12 "Title 12"  "Cat3" "25-03.2013 15:05"

结果将是:

26-03-2013
Post ID10 (15:05) CAT 3
POST ID8  (14:05) CAT 2
POST ID4  (13:05) CAT 1


25-03-2013
Post ID12 (15:05) CAT 3
POST ID6  (14:05) CAT 2
POST ID2  (13:05) CAT 1

1 个答案:

答案 0 :(得分:0)

尝试此查询,

$query ='SELECT categories.*, posts.* FROM categories, posts WHERE categories.id = posts.catID GROUP BY posts.catID ORDER BY posts.date DESC';

了解加入:http://dev.mysql.com/doc/refman/5.0/en/join.html

了解GROUP BY:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

了解ORDER BY:http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html

这可能对你有所帮助。