Distinct Query table with multiple category
I just wanna ask best practice
supposed I have three tables. posts, categories, post_Categories. One post can have one or many categories
Post
post_id post_title post_body
1 title 1 body1
2 title 2 body2
Categories
cat_id cat_name
1 C#
2 Java
3 PHP
posts_categories
pc_id pc_post pc_cat
1 1 1
2 1 2
3 1 3
4 2 2
5 2 开发者_运维技巧 3
I wanna display all post and its categries. and I can display list of post like this
title 1
body1
category(C#, Java, PHP)
-----------
title 2
body2
category(Java, PHP)
So I have to create query like this.
SELECT post_id, post_title, post_body, cat_id, cat_name
FROM posts p INNER JOIN post_categories pc ON p.post_id = pc.pc_post
INNER JOIN categories c ON c.cat_id = pc.cat_id
the result is
1 title 1 body1 1 C#
1 title 1 body1 2 Java
1 title 1 body1 3 PHP
2 title 2 body2 2 Java
2 title 2 body2 3 PHP
after that, I must loop the post, and check if the title1 still have any category. if have, I must temp it to some variable. if not I continue check the categories of title2 and temp it to some variable
after all, I display all post with its categories.
Is there any best practice than my code
You can use GROUP BY post_id
and have a GROUP_CONCAT(cat_name SEPARATOR ', ') AS categories
in you select list, but only if you don't want to work with the IDs of categories, e.g. make them links.
What you're doing is good practice.
You could simplify by removing the posts_categories
table, and just adding a cat_id field to the Post table.
精彩评论