简体   繁体   English

Mysql:从另一个表更新表的所有列

[英]Mysql: Update all columns of table from another table

I have two tables a_table and b_table and are initialised as:我有两个表 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');

I want to update a_table with the information from b_table, and can do so with the command我想用 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

What I would like to know is if there is a simpler way to list all the columns to update?我想知道的是是否有一种更简单的方法来列出要更新的所有列? so doing away with所以废除

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

Seems ok here as there are just two columns, but if there were 100s of columns this could get tedious.这里似乎没问题,因为只有两列,但如果有 100 列,这可能会变得乏味。 I want to avoid using我想避免使用

replace into a_table select * from b_table

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=bf179cbbfb090e78acf542c6ddeec0f5 to follow along the example above https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=bf179cbbfb090e78acf542c6ddeec0f5跟随上面的例子

One solution could be to create an array containing the column names, and then looping through the array to create一种解决方案可能是创建一个包含列名的数组,然后遍历该数组以创建

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

Would anyone be able to show how this could be done in Mysql?任何人都可以展示如何在 Mysql 中做到这一点?

Dear if there is only option of updating table rows from other table , you must mention all the columns if they are hundreds or thousands in count.亲爱的,如果只有从其他表更新表行的选项,你必须提到所有的列,如果它们是成百上千的。 If you want to insert rows from other table, then there is a simple way.如果你想从其他表插入行,那么有一个简单的方法。 The best and optimized way will be that: Write a script or code whatever you are best at.最好和优化的方法是:编写您最擅长的脚本或代码。 Put the columns in an array and make a query builder for this purpose.将列放在一个数组中并为此目的创建一个查询构建器。 Then run / execute the query.然后运行/执行查询。 looking forward for further assistance期待进一步的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM