• 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='评伦表';
    

    随便搞点测试数据

    我们运行如下语句:

    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。

  • 相关阅读:
    Android AlertDialog警告对话框实现
    Android状态栏通知Status Bar Notification
    Android spinner控件的实现
    Winform之UI后台线程
    Winform之自定义控件
    WebForm原理,aspx服务器端与客户端源码比较
    IHttpModule之闲扯
    [算法]方正面试题:N×N矩阵螺旋打印输出
    DOTA版设计模式——工厂方法
    Window服务
  • 原文地址:https://www.cnblogs.com/jkko123/p/10163068.html
Copyright © 2020-2023  润新知