简体   繁体   中英

SQL - Select all posts with comma separated values of categories with relations table between posts and categories

I wish to select the posts with the name of the categories with comma separated values like so:

posts table

id post_name post_content
1 first post first post content
2 second post second post content
3 third post third post content

relations table

relation_id post_id cat_id
1 1 1
2 1 4
3 1 5
4 2 4
5 2 5
6 3 2
7 3 3

categories table

cat_id cat_name cat_slug cat_desc
1 Cat One catone lorem ipsum one
2 Cat Two cattwo lorem ipsum two
3 Cat Three catthree lorem ipsum Three
4 Cat Four catfour lorem ipsum Four
5 Cat Five catfive lorem ipsum Five

Result:

id post_name post_content cat_slug cat_name
1 first post first post content catone,catfour,catfive Cat One, Cat Four, Cat Five
2 second post second post content catfour,catfive Cat Four, Cat Five
3 third post third post content cattwo,catthree Cat Two, Cat Three

I've tried group contact with no luck, its working with multiple queries and foreach loop, but I want to know if its possible to achieve this with only one query.

Did you try a join and group by ?

select p.*,
       group_concat(pc.cat_slug) as cat_slugs,
       group_concat(pc.cat_name) as cat_names
from posts p left join
     relations r
     on r.post_id = p.id left join
     post_categories pc
     on pc.cat_id = r.cat_id
group by p.id;

This works like a charm in my case. I also have 2 tables and 1 relation table just like yours. (MSSQL)

SELECT
     p.*
    ,STUFF((
          SELECT ',' + c.cat_name
          FROM categories c
          JOIN relations r ON r.post_id=p.id
          WHERE r.cat_id= c.cat_id
          FOR XML PATH('')), 1, 1, '') as Result
FROM posts p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM