Update

如何使用現有行中的數據更新某些表行?

  • February 20, 2020

我創建了一個表,其中儲存了一些具有這種結構的多語言商店數據

create table store_locator_store_lang
(
   id_store int(11) unsigned not null,
   lang_id int not null,
   partner varchar(100) null,
   address varchar(255) null,
   city varchar(100) null,
   occupation varchar(100) null,
   primary key (id_store, id_lang)
);

id_lang can be 1 or 2

在那裡我有一些不完整的數據,這意味著所有行都包含空值,lang_id = 1lang_id = 2許多行包含空值。

我想用來自行的lang_id = 2數據填充空行lang_id = 1

商店實體由 標識,id_store因此id_store對於同一商店的兩種語言來說是通用的。

即使一行有空列,也總是儲存一對。沒有機會缺少一行lang_id=2

是否可以通過數據庫中的更新查詢來完成此任務,還是我必須導出數據、編輯並重新插入?

數據庫伺服器是 10.1.44-MariaDB-0ubuntu0.18.04.1 Ubuntu 18.04

這是一些範例數據的轉儲

INSERT INTO store_locator_store_lang (id_store, lang_id, partner, address, city, occupation) VALUES (543, 1, 'TEST', 'TEST, Τ.Κ. 52100', 'TEST', 'TEST');
INSERT INTO store_locator_store_lang (id_store, lang_id, partner, address, city, occupation) VALUES (543, 2, '', '', '', '');

一般來說(如果“許多行包含空值”意味著“它們包含 NULL”):

UPDATE store_locator_store_lang t1
 JOIN store_locator_store_lang t2 ON t1.id_store = t2.id_store 
                                 AND t1.lang_id = 1
                                 AND t2.lang_id = 2
SET t2.partner = COALESCE(t2.partner, t1.partner),
   t2.address = COALESCE(t2.address, t1.address),
   t2.city = COALESCE(t2.city, t1.city),
   t2.occupation = COALESCE(t2.occupation, t1.occupation);

空值似乎是零長度字元串而不是空值。

UPDATE store_locator_store_lang t1
 JOIN store_locator_store_lang t2 ON t1.id_store = t2.id_store 
                                 AND t1.lang_id = 1
                                 AND t2.lang_id = 2
SET t2.partner = CASE WHEN t2.partner = ''
                     THEN t1.partner
                     ELSE t2.partner END,
   t2.address = CASE WHEN t2.address = ''
                     THEN t1.address 
                     ELSE t2.address END,
   t2.city = CASE WHEN t2.city = ''
                  THEN t1.city 
                  ELSE t2.city END,
   t2.occupation = CASE WHEN t2.occupation = ''
                        THEN t1.occupation 
                        ELSE t2.occupation END
/* WHERE '' IN (t2.partner, t2.address, t2.city, t2.occupation) */
   ;

引用自:https://dba.stackexchange.com/questions/260133