Reputation: 5939
So, I have two tables with 'articles' and 'tags' I am trying to fetch articles and their corresponding tags, with this code:
SELECT b.id, b.title, b.content, b.slug, b.created_at, GROUP_CONCAT(t.name) as tags
FROM blogs b INNER JOIN
tags t
ON b.id = t.blog_id
GROUP BY b.id, b.title;
The problem is that if an blogs has no tag, then I get no blogs, instead of getting the blog with no tags, how is this achievable
Upvotes: 0
Views: 43
Reputation: 919
I think what you are looking for is Left outer Join.
select b.id,b.title,b.content,b.slug,b.created_at,GROUP_CONCAT(t.name) as tags
from
blogs b left join tags t
on b.id = t.blog_id
group by b.id,b.title;
Upvotes: 0
Reputation: 1269633
You can use left join
:
SELECT b.id, b.title, b.content, b.slug, b.created_at,
GROUP_CONCAT(t.name) as tags
FROM blogs b LEFT JOIN
tags t
ON b.id = t.blog_id
GROUP BY b.id;
Normally, selecting a bunch of columns with a GROUP BY
would be bad style. However, blogs.id
is (presumably) unique in blogs
, so this is the one case where selecting other columns from blogs
is fine.
Upvotes: 1