因此,我修改了从该线程中学到的查询,但是当我在标签和猫之间进行过滤时,结果并不理想。过滤类别 5 将仅返回类别列表信息,标签将为空,而标签则相反。
SELECT posts.id,time,title,
GROUP_CONCAT(IFNULL(cats.id, '') ORDER BY cats.id DESC SEPARATOR '~') as catIdList,
GROUP_CONCAT(IFNULL(cats.name, '') ORDER BY cats.id DESC SEPARATOR '~') as catNameList,
GROUP_CONCAT(IFNULL(cats.slug, '') ORDER BY cats.id DESC SEPARATOR '~') as catSlugList,
GROUP_CONCAT(IFNULL(cats.value, '') ORDER BY cats.id DESC SEPARATOR '~') as catValueList,
GROUP_CONCAT(IFNULL(tags.id, '') ORDER BY tags.id DESC SEPARATOR '~') as tagIdList,
GROUP_CONCAT(IFNULL(tags.name, '') ORDER BY tags.id DESC SEPARATOR '~') as tagNameList,
GROUP_CONCAT(IFNULL(tags.slug, '') ORDER BY tags.id DESC SEPARATOR '~') as tagSlugList,
GROUP_CONCAT(IFNULL(tags.value, '') ORDER BY tags.id DESC SEPARATOR '~') as tagValueList
FROM posts
LEFT JOIN termRelations ON ( posts.id = termRelations.postId )
LEFT JOIN cats ON ( termRelations.termId = cats.id AND termRelations.termTypeId = 1 )
LEFT JOIN tags ON ( termRelations.termId = tags.id AND termRelations.termTypeId = 0 )
WHERE ( ( IFNULL(tags.id, '') = '4' ) )
GROUP BY posts.id ORDER BY time DESC
IFNULL() 可以解决不存在的条目。上面的查询将返回:
(
[id] => 15
[time] => 0
[title] => post 15
[catIdList] =>
[catNameList] =>
[catSlugList] =>
[catValueList] =>
[tagIdList] => 4
[tagNameList] => tagname
[tagSlugList] => tagname
[tagValueList] =>
)
(
[id] => 16
[time] => 0
[title] => post 16
[catIdList] =>
[catNameList] =>
[catSlugList] =>
[catValueList] =>
[tagIdList] => 4
[tagNameList] => tagname
[tagSlugList] => tagname
[tagValueList] =>
)
虽然没有WHERE ( ( IFNULL(tags.id, '') = '4' ) )
结果(当然,由于它没有被过滤到这个标签,所以还有所有其他帖子):
(
[id] => 15
[time] => 0
[title] => post 15
[catIdList] =>
[catNameList] =>
[catSlugList] =>
[catValueList] =>
[tagIdList] => 4
[tagNameList] => tagname
[tagSlugList] => tagname
[tagValueList] =>
)
(
[id] => 16
[time] => 0
[title] => post 16
[catIdList] => 5~~
[catNameList] => Movies~~
[catSlugList] => movies~~
[catValueList] => ~~
[tagIdList] => 4~1~
[tagNameList] => tagname~sand~
[tagSlugList] => tagname~sand~
[tagValueList] => ~~
)
这当然是我想要的 - 所有相关信息!
这些表是:
termRelations
包含 post ID 和 term ID,termTypeId 区分 cat 和 tags 表。cats
包含术语 ID 和类别信息(名称、slug、parentId 等)tags
包含术语 ID 和标签信息(名称、slug 等)posts
包含帖子信息(标题、时间、正文等)
termRelations 的目的是将标签和类别绑定到帖子。此查询的目的是返回过滤结果(我希望用户能够查看具有特定标签和特定类别的帖子。)同时仍保留完整信息。
是否有可能通过将cats
andtags
表组合成来解决这个问题terms
?
我希望我知道如何,但在这一点上,我几乎在这方面遇到了心理障碍。所以,一点帮助:)?谢谢!!