2

I have 3 tables that look like this -

  • content
    • cid
    • data
  • contenttags
    • cid
    • tid
  • tags
    • tid
    • tag

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

oh wow, that's exactly what I was looking for, thanks! But why does it exclude those entries which don't have any tags?
It shouldn't excludes them from the resultset since you are using LEFT joins. If you do not want it to return NULL, Try surrounding it with a IFNULL() ie IFNULL(GROUP_CONCAT(...),'') AS Tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.