使用SUBSTRING_INDEX,INSTR,REGEXP的溶液,具有完整的演示。
SQL:
-- data
create table t1(title varchar(100), code varchar(100));
insert into t1 values
('NWAB110438 Lagoon', 'NWAB110438 Lagoon'),
('Lagoon NWAB110438', 'Lagoon NWAB110438'),
('Lagoon', 'Lagoon'),
('NWAB110438', 'NWAB110438');
select * from t1;
-- query wanted
UPDATE t1
SET
title = TRIM(CONCAT(IF((@first := SUBSTRING_INDEX(title, ' ', 1)) REGEXP '[0-9]+', '', @first),
' ',
IF((@second := IF(INSTR(title, ' '), SUBSTRING_INDEX(title, ' ', -1), '')) REGEXP '[0-9]+', '', @second))),
code = TRIM(CONCAT(IF(@first REGEXP '[0-9]+', @first, ''),
' ',
IF(@second REGEXP '[0-9]+', @second, '')));
select * from t1;
輸出:
mysql> select * from t1;
+-------------------+-------------------+
| title | code |
+-------------------+-------------------+
| NWAB110438 Lagoon | NWAB110438 Lagoon |
| Lagoon NWAB110438 | Lagoon NWAB110438 |
| Lagoon | Lagoon |
| NWAB110438 | NWAB110438 |
+-------------------+-------------------+
4 rows in set (0.00 sec)
mysql> UPDATE t1
-> SET
-> title = TRIM(CONCAT(IF((@first := SUBSTRING_INDEX(title, ' ', 1)) REGEXP '[0-9]+', '', @first),
-> ' ',
-> IF((@second := IF(INSTR(title, ' '), SUBSTRING_INDEX(title, ' ', -1), '')) REGEXP '[0-9]+', '', @second))),
-> code = TRIM(CONCAT(IF(@first REGEXP '[0-9]+', @first, ''),
-> ' ',
-> IF(@second REGEXP '[0-9]+', @second, '')));
Query OK, 4 rows affected (0.00 sec)
Rows matched: 4 Changed: 4 Warnings: 0
mysql> select * from t1;
+--------+------------+
| title | code |
+--------+------------+
| Lagoon | NWAB110438 |
| Lagoon | NWAB110438 |
| Lagoon | |
| | NWAB110438 |
+--------+------------+
4 rows in set (0.00 sec)
有'NWAB110438'和'Lagoon'之間的空間? – Sadikhasan
是的,它們之間有空間。 – Tyssen