-1

I wanted to load all my post tags with a single query into the MySQL server.

Now, I have decided to use LEFT JOIN because if there is no tags are associated with my post then also I will have that post, or you have any other suggestion for this?
Here is my query:

SELECT * FROM tags, tags_map 
LEFT JOIN posts on posts.cid = tags_map.pid 
WHERE tags.tag_id = tags_map.tid

Now the problem is duplicate data, for example if a post has three tags then the post itself will repeat three time!
In this case should I run another query for each post to have their tags? or can i get them all with a single query but without duplicate data?

Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73
rakibtg
  • 5,521
  • 11
  • 50
  • 73

1 Answers1

1

I think you want group_concat

SELECT posts.*, 
   (select GROUP_CONCAT(tags.name)
    from  tags, 
      tags_map 
LEFT JOIN  on posts.cid = tags_map.pid 
WHERE tags.tag_id = tags_map.tid) as tagCombo
from posts

If you post a schema, sample data and expected results, ideally as a SQLFiddle, I can check.

Community
  • 1
  • 1
Neville Kuyt
  • 29,247
  • 1
  • 37
  • 52