首页 > 解决方案 > Mysql:从另一个表更新表的所有列

问题描述

我有两个表 a_table 和 b_table 并初始化为:

create table a_table(
id int not null auto_increment primary key,
reference varchar(255),
colour varchar(255),
size varchar(255),
unique (reference)
);

insert into a_table (reference, colour, size) values
('ref1', 'red', 'big'),
('ref2', 'blue', 'small'),
('ref3', 'green', 'mini');
create table b_table(
id int not null auto_increment primary key,
reference varchar(255),
colour varchar(255),
size varchar(255),
unique (reference)
);

insert into b_table (reference, colour, size) values
('ref1', 'orange', 'tiny'),
('ref2', 'orange', 'tiny'),
('ref3', 'orange', 'tiny'),
('ref4', 'pink', 'large'),
('ref5', 'yellow', 'huge'),
('ref6', 'purple', 'small');

我想用 b_table 中的信息更新 a_table,并且可以使用命令

update a_table a, b_table b
set a.colour = b.colour,
a.size = b.size
where
a.reference = b.reference

我想知道是否有更简单的方法来列出所有要更新的列?所以取消

a.colour = b.colour,
a.size = b.size

这里似乎没问题,因为只有两列,但如果有 100 列,这可能会变得乏味。我想避免使用

replace into a_table select * from b_table

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=bf179cbbfb090e78acf542c6ddeec0f5跟随上面的例子

一种解决方案可能是创建一个包含列名的数组,然后遍历该数组以创建

a.colour = b.colour,
a.size = b.size

谁能展示如何在 Mysql 中做到这一点?

标签: mysqlsqlmariadb

解决方案


亲爱的,如果只有从其他表更新表行的选项,您必须提及所有列,如果它们有数百或数千个。如果要从其他表中插入行,那么有一种简单的方法。最好的和优化的方法是:编写你最擅长的脚本或代码。将列放在一个数组中,并为此创建一个查询生成器。然后运行/执行查询。期待进一步的帮助


推荐阅读