1

我有一个名为categories的表和一个名为posts. 每个帖子都有日期、标题、id 和 catID。如何进行查询以返回按日期排序的每个类别的第一篇文章。

例子:

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
4

1 回答 1

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

这可以帮助你。

于 2013-03-26T09:36:39.700 回答