类别
id -- PK
pid -- FK to self (id), allow NULL
name
description
slug
标签
id -- PK
name
description
slug
Cat_Rel
id -- PK
pid -- FK: Post Id
cid -- FK: Category Id
Tag_Rel
id -- PK
pid -- FK: Post Id
tid -- FK: Tag Id
我需要在一个查询中得到这个结果: 行:pid |标签1,标签2,标签3 |类别1,类别5
最佳答案
我将使用两个子查询和union all
来完成此操作:
select pid, max(tags), max(cats)
from ((select t.pid, group_concat(t.name) as tags, NULL as cats
from tag_rel tr join
tags t
on tr.tid = .tid
group by t.pid
) union all
(select c.pid, NULL, group_concat(c.name) as cats
from cat_rel cr join
cats c
on cr.cid = c.id
)
) ct
group by pid;
这将确保您获得所有帖子,即使是那些没有标签和/或没有类别的帖子。
关于php - mysql选择关系两个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27213570/