mysql left join 多条记录 1:n 的处理方法

前端之家收集整理的这篇文章主要介绍了mysql left join 多条记录 1:n 的处理方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、准备两张表,文章表和评伦表

CREATE TABLE `article` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',`title` varchar(255) DEFAULT '' COMMENT '文章标题',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文章表';

CREATE TABLE `comment` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',`a_id` int(11) DEFAULT '0' COMMENT '文章ID',`content` varchar(255) DEFAULT '' COMMENT '评伦内容',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='评伦表';

随便搞点测试数据

@H_502_10@

 

我们运行如下语句:

select * from article as a left join comment as c on c.a_id = a.id;

结果如上所示,主表中有多条记录重复显示了,因为条件 on c.a_id = a.id 主表中的一条记录对应右表中的多条记录,这种1 : n 的情况,

left join 的处理方法是主表以重复的方式对应多条右表记录出现在结果集中。

但是这显然不是我们想要的。我们想要以 article 为主表,1 : 1 的显示右表数据。

 

方法一:使用group by ,找出右表一条记录与主表关联

select * from article as a 
left join (select id,a_id,content from comment group by a_id) as c 
on c.a_id = a.id;

方法二:使用group by 和 min或max聚合函数,找出右表最新或最旧的一条记录与主表关联

select * from article as a 
left join (select * from comment where id in (select max(id) from comment group by a_id)) as c 
on c.a_id = a.id;

方法三:使用group_concat

select * from article as a
left join (select a_id,group_concat(concat(id,',content) order by id desc separator '_') from comment group by a_id) as c
on c.a_id = a.id;

所有解决办法,都是一个出发点,使主表与右表的对应关系为1 : 1。

 

猜你在找的MySQL相关文章