how can I update some table rows using data from existing rows?
-
24-02-2021 - |
Question
I have created a table where it stores some multilingual store data with this structure
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
In there I have some incomplete data meaning that there are all the rows for lang_id = 1
but for lang_id = 2
many rows contain empty values.
I would like to populate the empty rows for lang_id = 2
with data from the rows with lang_id = 1
.
The store entity is identified by id_store
so the id_store
is common for the two languages of the same store.
There is always a pair stored even if one row has empty columns. There is no chance there is a row missing for lang_id=2
Is it possible to accomplish this task with an update query in the database or do I have to export the data, edit and reinsert?
The Database server is 10.1.44-MariaDB-0ubuntu0.18.04.1 Ubuntu 18.04
Here's a dump of some example data
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, '', '', '', '');
Solution
In general (if "many rows contain empty values" means "they contains 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);
The empty value seems to be zero-length string and not 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 = 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) */
;