1
I use the query below to return all posts marked with the tag set:
SELECT imprensa_posts.slug AS slug, tipo, titulo, data
FROM imprensa_posts
JOIN imprensa_tags_posts ON imprensa_tags_posts.id_post = imprensa_posts.id_post
JOIN imprensa_tags ON imprensa_tags.id_tag = imprensa_tags_posts.id_tag
WHERE imprensa_tags.slug = 'tag-4'
ORDER BY data DESC
But I also need to get all the tags associated with each returned post. I tried this way:
SELECT imprensa_posts.slug AS slug, tipo, titulo, data,
GROUP_CONCAT(imprensa_tags.slug) AS tag_slugs, GROUP_CONCAT(tag) AS tags
FROM imprensa_posts
JOIN imprensa_tags_posts ON imprensa_tags_posts.id_post = imprensa_posts.id_post
JOIN imprensa_tags ON imprensa_tags.id_tag = imprensa_tags_posts.id_tag
WHERE imprensa_tags.slug = 'tag-4'
GROUP BY imprensa_posts.id_post
ORDER BY data DESC
But it doesn’t work. The query returns tag-4 for all posts.
UPDATE
I recreated the tables in SQL Fiddle: http://sqlfiddle.com/#! 9/3c04b/5
It’s returning the same result. Both queries work correctly except for one point: if a given post is associated with a tag that is not the one reported in WHERE, it is not shown in the Group_concats
– marcelo2605
@marcelo2605 but you don’t want to filter the posts only to those who have the
'tag-4'
related?– Maicon Carraro
@marcelo2605 I think I understand what you mean, I’ll change it.
– Maicon Carraro
@marcelo2605 I changed the SELECT of
EXISTS
, check– Maicon Carraro
There’s something wrong: Error Code: 1054. Unknown column 'itg.id_post' in 'Where clause'
– marcelo2605
@marcelo2605 was
itp
, already corrected.– Maicon Carraro
It’s returning the same thing. It returns all posts linked to tag-4. But if the post is also linked to another tag, this appears in Group_concats
– marcelo2605
@marcelo2605 You executed exactly the example I suggested?
– Maicon Carraro
@marcelo2605 I put another solution with 2
sub select
, of a verified.– Maicon Carraro
Same thing. I will create a SQL Fiddle and put here.
– marcelo2605
@Marcelo2605 It will help a lot :/
– Maicon Carraro
I asked the question. Run the first query and see that Release 2 is linked to two tags (tag 1 and tag 7). But when I run the second query, only the 1 tag appears.
– marcelo2605
@marcelo2605 the first select I made with
EXISTS
is correct not? here brought right tag1 and tag7– Maicon Carraro
@marcelo2605 I arranged the with 2
sub select
, now it’s returning like the first– Maicon Carraro
It worked! Thank you very much.
– marcelo2605