简体   繁体   English

MySQL连接:即使secon表没有匹配数据,如何从一个表中获取结果

[英]MySQL join: How to get result from one table even if secon table has no matching data

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 问题是,如果博客没有标签,那么我没有博客,而不是没有标签的博客,这是如何实现的

You can use left join : 您可以使用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. 通常,选择一堆带有GROUP BY的列是不好的样式。 However, blogs.id is (presumably) unique in blogs , so this is the one case where selecting other columns from blogs is fine. 但是, blogs.idblogs (可能)是唯一的,因此这是从blogs中选择其他列的一种情况。

I think what you are looking for is Left outer Join . 我认为您正在寻找的是Left external 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM