Mysql

從一列中刪除子字元串並將其放在另一列

  • September 2, 2018

我有一張這樣的桌子:

CREATE TABLE `mytable` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`column1` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`column2` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

還有一些數據:

id | column1                                       | column2
____________________________________________________________
1  | Something                                     |
2  | Something else - Lets add more data           |
3  | Something else - Another example - More stuff |

我想更新此表,將第一個-(空格+破折號+空格)之後的所有內容放入 column2,然後將其從第 1 列中刪除。如果沒有-,請保持原樣。比如這樣:

id | column1        | column2
__________________________________________________
1  | Something      |
2  | Something else | Lets add more data
3  | Something else | Another example - More stuff

有什麼建議?

UPDATE mytable
SET column2 = SUBSTRING(column1, 3 + LENGTH(SUBSTRING_INDEX(column1, ' - ', 1))),
   column1 = SUBSTRING_INDEX(column1, ' - ', 1)
SELECT column1, LEFT(column1, Position(' - ' in column1)) as newCol1,  
substring(column1, Locate(" - ",column1)+3) as newCol2 
FROM mytable where column1 like '% - %';

這應該讓你朝著正確的方向前進。如果它為您提供了您想要的結果,您可以使用它來創建您的更新語句。

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