I have two tables, one for posts, one for tags related to posts, where posts.tags holds the ids of the tags related to the post.
posts:
id | title | tags
-----------------
1 | Foobar | 1 3 7
2 | Barfoo | 2 3 7
tags:
id | tag
--------
1 | Tag1
2 | Tag2
... and so forth
When querying for a post, I would like to get a post with all its tags as space-seperated string, instead of the string of tag ids.
I tried a query like:
SELECT *,
(
SELECT GROUP_CONCAT(tags.tag)
FROM tags
WHERE tags.id LIKE 1 OR tags.id LIKE 3
) AS tag_str
FROM posts
This basically outputs what I am looking for; What I can’t figure out is the correct WHERE condition in the subclause, that would check, in my own words, “for tags WHERE tag.id matches any space-seperated number-string in posts.tags” – if any such query is possible?
Any help appreciated,
k.
Your fundamental database design is flawed and now you’re suffering the consequences of that flaw. If you have any possibility of fixing this, you should do so. The tags should not be stored as a space-delimited string in a single column of the Posts table. Instead, you should have a junction table,
Posts_Tags_xref, that would resolve the many-to-many relationship. This table would consist of two foreign keys,Posts.idandTags.id.For your sample data above, you’d have:
And the query you’re asking for becomes: