2

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))));
4

1 回答 1

2

尝试这样的事情:

UPDATE data 
   SET data = CONCAT('word=',(SELECT id 
                                FROM words 
                               WHERE words.word = SUBSTRING_INDEX(data.data,'=',-1)))

抱歉,我这里没有 MySql 来测试它(特别确保 SUBSTRING 在 'word=' 之后得到所有内容)

编辑:我使用带有 -1 的 substring_index 来获取 = 符号的最后一个索引。

于 2012-07-03T21:20:47.557 回答