mysql - 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 中做到这一点?
解决方案
亲爱的,如果只有从其他表更新表行的选项,您必须提及所有列,如果它们有数百或数千个。如果要从其他表中插入行,那么有一种简单的方法。最好的和优化的方法是:编写你最擅长的脚本或代码。将列放在一个数组中,并为此创建一个查询生成器。然后运行/执行查询。期待进一步的帮助
推荐阅读
- rust - 当我在 Windows 上运行我的 rust 应用程序时,着色与 cargo run 一起工作,但在直接使用二进制文件时它会完全中断。为什么?
- angular - 使用 angular mat-autocomplete 节省 (focusout)
- terraform - 是否可以将 terraform 远程状态包装到模块中并从状态中输出变量?
- javascript - url 上的正则表达式并将页面发送到正确的组件
- ipfs - 如何实现 ipfs-pubsub-room 的可靠性
- java - 如何创建一个检查每个 int 的 for 循环
- r - 将列附加到 data.table,排序并避免 setDT
- r - 堆积条形图ggplot2-按特定变量排序样本,从最高到最低值
- sql-server - SQL Server PowerShell 提供程序错误:无法连接
- sharepoint-online - Sharepoint 下载 .aspx 而不是呈现页面