php - mysql select relation two items

299

Categories

id -- PK
pid -- FK to self (id), allow NULL
name
description
slug

Tags

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

I need this result in one query: row : pid | tag1,tag2,tag3 | cat1,cat5

235

Answer

Solution:

I would do this with two subqueries andunion 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;

This will ensure that you get all posts, even those with no tags and/or no categories.

People are also looking for solutions to the problem: php - Laravel Eloquent create returning null id

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.