【发布时间】:2016-12-25 14:22:21
【问题描述】:
我想在外部应用程序中为每个类别获取最新的 5 个已发布的 WordPress 帖子。这些应用程序是在 ASP.NET 中构建的,所以我想使用 EF 直接从 MySQL 数据库中获取数据。在 EF 中构建 WordPress 关系似乎很糟糕,所以我想构建一个自定义模型,其中包含有关最新帖子的类别详细信息和信息。
所以我写了一个有效的 SQL 查询,但是因为它的聚合组只给了我每个类别的一行(帖子):
Select terms.term_id As Id, terms.name As Name, terms.slug As SeoName, Group_Concat(relations.object_id) As PostId, taxonomy.count As Count, taxonomy.parent As ParentId,
(
Select post_title
From wp_posts
Where ID In(Group_Concat(relations.object_id))
Order By post_date Desc
) As PostTitle
From wp_terms terms, wp_term_taxonomy taxonomy, wp_term_relationships relations
Where terms.term_id = taxonomy.term_id
And relations.term_taxonomy_id = taxonomy.term_taxonomy_id
And taxonomy.taxonomy = 'category'
Group By terms.term_id
我的想法是添加 Having Count(terms.term_id) = 5 以便每个类别有 5 行。但它不起作用,我得到了一个空的结果。如果没有Having,我会在每个类别中获得一条带有最新帖子的行。
如何告诉 MySQL 每个类别返回 5 行而不删除分组?
假设我有树类别:
- CatA
- 猫B
- CatC
那我想从数据库中得到如下结果(简而言之):
CategoryId | CategoryName | NewestPostTitle
1 | CatA | Newest post in CatA
1 | CatA | Second newest post in CatA
...
2 | CatB | Newest post in CatB
2 | CatB | Second newest post in CatB
...
3 | CatC | Newest post in CatC
3 | CatC | Second newest post in CatC
【问题讨论】:
-
如果您愿意,请考虑遵循以下简单的两步操作: 1. 如果您还没有这样做,请提供适当的 CREATE 和 INSERT 语句(和/或 sqlfiddle),以便我们可以更容易复制问题。 2. 如果您尚未这样做,请提供与步骤 1 中提供的信息相对应的所需结果集。
-
你为什么不用简单的 WP_Query(或 get_posts())遍历类别,并通过每次迭代查询帖子?