我有一个文章系统,其中的文章可以在不同的部分,如食谱,如何,编辑,新闻等。
这些文章中的每一篇也可以属于一个或多个类别。例如,食谱可以分为松饼类和蓝莓类。
然后,当我生成url时,它的格式是:
example.com/{post_section}/{primary_post_category_slug}/{post_title}/在列出文章时,在标题的上方,我将显示文章所包含的每个类别。这些类别中的每一个都是一个链接,当单击该链接时,只显示属于该类别的文章。
我的问题是,当列出一个类别中的所有文章时,如果一篇文章有多个类别,我就无法知道如何检索主项目。例如,如果我有一篇文章是蓝莓松饼的配方,我会把它放在第一类松饼和第二类蓝莓中。
现在,如果访问者浏览蓝莓类别,它应该列出所有与蓝莓相关的文章,但是链接仍然应该包含任何主要类别的片段。我的问题是检索主类别时,它不同于我们要列出的类别。
下面是我使用的示例查询和表结构:
select p.*, c.*, t.* from posts p
left join post_category_selected a on a.post_id = p.post_id
left join post_category c using (post_category_id)
left join post_section t using (post_section_id)
and c.post_category_slug = "blueberry"
and t.post_section_slug = "recipes"
order by p.post_publish_date desc这确实返回所有有蓝莓类的文章,但我不知道如何检索松饼的primary_category,以便在生成链接时使用它。
希望这是有意义的。
表结构:
posts
|- post_id
|- post_title
|- post_section
|- post_slug
|- post_publish_date
post_category
|- post_category_id
|- post_section_id
|- post_category
|- post_category_slug
post_category_selected
|- post_category_selected_id
|- post_id
|- post_category_id
|- is_primary (enum Y,N)
post_section
|- post_section_id
|- post_section_title
|- post_section_slug发布于 2016-01-20 23:11:40
您需要分别加入两次post_category和post_category_selected,一次用于选定的类别,一次用于主类别。如下所示:
select p.*, c1.*, t.*,
c2.post_category_slug as primary_category_slug
from posts p
left join post_category_selected a1 on a1.post_id = p.post_id
left join post_category c1 using (post_category_id)
left join post_section t using (post_section_id)
and c.post_category_slug = "blueberry"
and t.post_section_slug = "recipes"
left join post_category_selected a2 on a2.post_id = p.post_id
and a2.is_primary = 'Y'
left join post_category c2 on c2.post_category_id = a2.post_category_id
order by p.post_publish_date desc您可能需要从c2添加一些额外的列,这取决于您的其他需求。
https://stackoverflow.com/questions/34910127
复制相似问题