mysql中燕十八:一道面试题使用union all实现两张表id相同的num值相加。 您所在的位置:网站首页 两张表相加 mysql中燕十八:一道面试题使用union all实现两张表id相同的num值相加。

mysql中燕十八:一道面试题使用union all实现两张表id相同的num值相加。

2024-06-30 06:03| 来源: 网络整理| 查看: 265

(1)先创建两张表,分别为a,b create table a ( id char(1), num int )engine myisam charset utf8;

insert into a values (‘a’,5),(‘b’,10),(‘c’,15),(‘d’,10);

create table b ( id char(1), num int )engine myisam charset utf8;

insert into b values (‘b’,5),(‘c’,15),(‘d’,20),(‘e’,99); 在这里插入图片描述 (2)解决办法: 思路:先把两张表的数据合并到一块,再利用sum来相加 1、使用union select id, sum(num) from (select * from a union select * from b) as tmp group by id; 在这里插入图片描述 结果出现错误,由于两张表都出现c=15,而union是去重的,所以这里使用union all。 2、使用union all实现结果的不去重 select id, sum(num) from (select * from a union all select * from b) as tmp group by id; 在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有