【发布时间】:2026-01-31 10:35:01
【问题描述】:
所以,我修改了从this thread 学到的查询,但是当我在标签和猫之间进行过滤时,结果并不理想。过滤类别 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 和tags 表合并到terms 中来解决这个问题?
我希望我知道怎么做,但是在这一点上,我几乎碰到了心理障碍。所以,一点帮助:)?谢谢!!
【问题讨论】:
标签: php mysql join table-relationships