MySQL 选择关系两个项目


mysql select relation two items

类别

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;

这将确保您获得所有帖子,即使是那些没有标签和/或没有类别的帖子。