簡體   English   中英

Mysql:從另一個表更新表的所有列

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

我有兩個表 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 中做到這一點?

親愛的,如果只有從其他表更新表行的選項,你必須提到所有的列,如果它們是成百上千的。 如果你想從其他表插入行,那么有一個簡單的方法。 最好和優化的方法是:編寫您最擅長的腳本或代碼。 將列放在一個數組中並為此目的創建一個查詢構建器。 然后運行/執行查詢。 期待進一步的幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM