P粉3015232982023-08-18 13:51:58
需要考虑的一些要点。
根据问题
考虑以下数据示例,其中FullName
列最多由三个用空格分隔的单词组成
create table NameTable ( ID int, FullName varchar(100), age int, primary key(ID) ); insert into NameTable (ID, FullName, age) values (1, 'ben thompson', 23), (2, 'Martin Luther King', 23);
查询,
SELECT SUBSTRING_INDEX(TRIM(FullName), ' ', -1) LastName, SUBSTRING_INDEX(TRIM(FullName), ' ', 1) FirstName, SUBSTR(FullName, LOCATE(' ',FullName) + 1, (CHAR_LENGTH(FullName) - LOCATE(' ',REVERSE(FullName)) - LOCATE(' ',FullName))) AS MiddleName FROM NameTable;
结果,
LastName FirstName MiddleName Thompson Ben King Martin Luther
首先通过修改表结构来进行更改,如果有大量的事务,我建议适当锁定表
SET autocommit=0; LOCK TABLES NameTable WRITE; alter table NameTable add column FullNameReverseOrder varchar(100) after FullName; COMMIT; UNLOCK TABLES;
要更新新添加的列LastName,MiddleName和FirstName,请使用以下命令:
update NameTable set FullNameReverseOrder = concat_ws(' ' ,SUBSTRING_INDEX(TRIM(FullName), ' ', -1), SUBSTR(FullName, LOCATE(' ',FullName)+1, (CHAR_LENGTH(FullName) - LOCATE(' ',REVERSE(FullName)) - LOCATE(' ',FullName))), SUBSTRING_INDEX(TRIM(FullName), ' ', 1) );
选择,
select * from NameTable;
结果
ID FullName FullNameReverseOrder age 1 ben thompson thompson ben 23 2 Martin Luther King King Luther Martin 23
现在,如果您希望该过程自动进行,请考虑创建一个触发器。
CREATE TRIGGER FullNameReverseOrderUpdate BEFORE INSERT ON NameTable FOR EACH ROW BEGIN SET new.FullNameReverseOrder = (concat_ws(' ' ,SUBSTRING_INDEX(TRIM(new.FullName), ' ', -1), SUBSTR(new.FullName, LOCATE(' ',new.FullName)+1, (CHAR_LENGTH(new.FullName) - LOCATE(' ',REVERSE(new.FullName)) - LOCATE(' ',new.FullName))),SUBSTRING_INDEX(TRIM(new.FullName), ' ', 1) )); END;
插入测试值
insert into NameTable (ID, FullName, age) values (3, 'Arthur Thompson', 23); select * from NameTable;
结果
ID FullName FullNameReverseOrder age 1 ben thompson thompson ben 23 2 Martin Luther King King Luther Martin 23 3 Arthur Thompson Thompson Arthur 23