0

I have a blog posts table and a blog post tags table. One post has many tags. I first did this with a call to posts then a loop and call the tags table, but this resulted in 9 queries per page just to get the posts. I have rewritten this to use a join, but it returns duplicate blog posts rows.

SELECT p.timestamp
     , p.title
     , p.postcontent
     , p.siteid
     , t.tag 
  FROM user_blogposts p
  LEFT 
  JOIN user_blogposttags t
    ON t.postid = p.id 
 WHERE p.userid = 1 
 LIMIT 8

This query returns the data I want, but if there are 5 tags per post, each post will be duplicated 5 times with only the tag field being different. I can't use GROUP BY as this will return 1 row with 1 tag for each post and break the one to many connection.

Is there a way to return an array for the many join so that I only get 1 row for the post and then the tag column is an array or comma delimited string for me to work with rather than having to filter out all of the duplicate data.

Dan Hastings
  • 3,241
  • 7
  • 34
  • 71

2 Answers2

1

This query should work for you:

SELECT user_blogposts.*, (SELECT GROUP_CONCAT(tag) FROM user_blogposttags WHERE user_blogposttags.postid=user_blogposts.id) AS tags
FROM user_blogposts

May need minor changes as per your table structure

Sanchit
  • 541
  • 2
  • 18
1

You can group and concat the tags like this:

SELECT p.timestamp, p.title, p.postcontent, p.siteid, 
 GROUP_CONCAT(t.tag SEPERATOR ",") AS tags
FROM user_blogposts p
LEFT JOIN user_blogposttags t
ON t.postid = p.id 
GROUP BY p.timestamp, p.title, p.postcontent, p.siteid;
  • thanks for the response. There was another answer that used the same method posted first, but i gave an upvote for your answer as the GROUP_CONCAT solution worked perfectly. thank you – Dan Hastings Jan 18 '16 at 13:05