Mysql:关联表批量更新

问题和背景

我们在写 sql 语句的时候,经常会涉及到关联表更新,举例:
下面有两个表 userkpi_ratio,下面想计算 user 表每个人的 kpi(现在是0),两个表的 id 是可以关联的,公式 kpi = 100 * ratio

user 表:
+----+--------------+-----+
| id | name         | kpi |
+----+--------------+-----+
|  1 | 贝克汉姆      |   0 |
|  2 | 姆巴佩        |   0 |
|  3 | 卡卡          |   0 |
+----+--------------+-----+

kpi_ratio 表:
+----+-------+
| id | ratio |
+----+-------+
|  1 |   0.5 |
|  2 |   0.7 |
|  3 |     0 |
+----+-------+

update inner join 解决

update user u inner join kpi_ratio kr on u.id = kr.id
set u.kpi = 100 * kr.ratio where 1=1 -- where 1=1 是为了安全执行sql,与逻辑无关
-- 或者
update user u, kpi_ratio kr
set u.kpi = 100 * kr.ratio
where u.id = kr.id

执行结果正确:

+----+--------------+-----+
| id | name         | kpi |
+----+--------------+-----+
|  1 | 贝克汉姆     |  50 |
|  2 | 姆巴佩       |  70 |
|  3 | 卡卡         |   0 |
+----+--------------+-----+

建表语句

-- 创建员工表
create table user
(
    id int auto_increment comment '主键id',
    name varchar(32) default '' not null comment '名字',
    kpi int default 0 not null comment '绩效',
    constraint user_pk
        primary key (id)
)
comment '员工';

-- 绩效系数表
create table kpi_ratio
(
    id int not null comment '员工id',
    ratio double default 0 not null,
    constraint kpi_ratio_pk
        primary key (id)
)
comment '绩效系数';

-- 插入数据
insert into user(name, kpi) values ('贝克汉姆', 0);
insert into user(name, kpi) values ('姆巴佩', 0);
insert into user(name, kpi) values ('卡卡', 0);
insert into kpi_ratio values (1, 0.5);
insert into kpi_ratio values (2, 0.7);
insert into kpi_ratio values (3, 0);

简书作者 小菜荔枝原创 转载请联系作者获得授权

猜你喜欢

转载自blog.csdn.net/weixin_33787529/article/details/86795863