Reputation: 1138
With the following query:
SELECT p.*, i.*, GROUP_CONCAT(DISTINCT(pc.category_id)) AS post_categories, GROUP_CONCAT(DISTINCT(pt.tag_id)) AS post_tags
FROM posts AS p
LEFT JOIN images AS i ON p.post_image = i.image_id
LEFT JOIN post_categories AS pc ON p.post_id = pc.post_id
LEFT JOIN post_tags AS pt ON p.post_id = pt.post_id
WHERE p.post_url="'.$id.'"
I'm returning a list of blog posts, retrieving:
category_id
's (for the post)tag_id
's (for the post)What this leaves me with, are two fields that aren't really helpful:
I would really like to do a subquery within both of the LEFT JOINS
that allows me to, instead, return a list of:
category_name
's (i.e. "meditation,sports")tag_name
's (i.e. "iOS,PHP,MySQL")for each post.
I'm stuck right now on the subquery for both categories, and tags.
The table structures:
posts
post_id, post_title, etc.
categories
category_id, category_name
tags
tag_id, tag_name
post_categories
post_id, category_id
post_tags
post_id, tag_id
The question: is it possible to do such a thing effectively, if so, how?
If not, should I just store SELECT * FROM categories
in a $categories
array, then compare each category_id
in the $categories
array to each post's exploded category_id
string in the $posts
array each time?
Upvotes: 1
Views: 555
Reputation: 102793
You should be able to join to the tags and categories table, then just replace your concatenation with the name fields. (Also have to add Distinct to the select so as to not return duplicated main rows.)
SELECT DISTINCT p.*, i.*,
GROUP_CONCAT(DISTINCT(c.category_name)) AS post_categories,
GROUP_CONCAT(DISTINCT(t.tag_name)) AS post_tags
FROM posts AS p
LEFT JOIN images AS i ON p.post_image = i.image_id
LEFT JOIN post_categories AS pc ON p.post_id = pc.post_id
LEFT JOIN post_tags AS pt ON p.post_id = pt.post_id
LEFT JOIN categories AS c ON pc.category_id = c.category_id
LEFT JOIN tags AS t ON pt.tag_id = t.tag_id
WHERE p.post_url="'.$_GET['id'].'"
Upvotes: 1
Reputation: 48179
Then why not just grab the respective category name and tags description instead of their IDs in your GROUP_CONCAT
Upvotes: 1