I have a table which has two columns (id and word). I have an other table which has a data column and its value references the word in the first table. Here is a sample code:
CREATE TABLE `words` (
`id` TINYINT,
`word` VARCHAR(50),
PRIMARY KEY (`id`)
);
INSERT INTO `words` VALUES (1, 'one'), (2, 'two'), (3, 'three');
CREATE TABLE `data` (
`data` TEXT
);
INSERT INTO `data` VALUES ('foo=bar\nword=one'), ('word=three');
I would like to replace the references of words to ids. So word=one
would become word=1
, word=three
would become word=3
and so on. I tried this query, but it doesn't work:
UPDATE `data`, `words` SET `data`.`data` = REPLACE(`data`.`data`, CONCAT('word=', `words`.`word`), CONCAT('word=', `words`.`id`));
Any suggestion or idea how to achieve what I want? Thanks!
Edit: Forgot to mention that data column is in INI format, so other key-value pairs can be in fields too. Adjusted the example.
Edit: Thanks to the idea of @nortphole I managed to build the query that I need:
UPDATE `data` SET `data`.`data` = REPLACE(`data`.`data`, CONCAT('word=', SUBSTRING_INDEX(SUBSTRING_INDEX(`data`.`data`, 'word=', -1), '\n', 1)), CONCAT('word=', (SELECT `id` FROM `words` WHERE `words`.`word` = SUBSTRING_INDEX(SUBSTRING_INDEX(`data`.`data`, 'word=', -1), '\n', 1))));