allanminium
allanminium

Reputation: 139

php/mySQL How do I get all the tags from the database for multiple items?

I have 3 tables that look like this -

I'm trying to select 5 items from the content table whilst display every tag associated with the content. Here's what I have -

SELECT c.*, t.tag FROM content AS c LEFT JOIN contenttags AS ct ON c.cid = ct.cid LEFT JOIN tags AS t ON ct.tid = t.tid LIMIT 5

But all I seem to get is a whole lot of duplicate rows with the only difference being the tag. I thought ideally, all the tags could be merged in sql into one field? I dunno, am I going about this all wrong?

Upvotes: 2

Views: 419

Answers (1)

The Scrum Meister
The Scrum Meister

Reputation: 30111

you can use the GROUP_CONCAT() function, which will return the tags comma delimited:

SELECT c.*, GROUP_CONCAT(t.tag) AS Tags
FROM content AS c 
  LEFT JOIN contenttags AS ct ON c.cid = ct.cid 
  LEFT JOIN tags AS t ON ct.tid = t.tid 
GROUP BY c.cid 
LIMIT 5

Upvotes: 3

Related Questions