Rumah > Soal Jawab > teks badan
P粉3015232982023-08-18 13:51:58
Beberapa perkara yang perlu dipertimbangkan.
Berdasarkan soalan
Pertimbangkan contoh data berikut di mana FullName
lajur terdiri daripada sehingga tiga perkataan yang dipisahkan oleh ruang
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);
Pertanyaan,
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;
Keputusan,
LastName FirstName MiddleName Thompson Ben King Martin Luther
Mula-mula buat perubahan dengan mengubah suai struktur jadual Jika terdapat banyak urus niaga, saya cadangkan untuk mengunci jadual dengan sewajarnya
SET autocommit=0; LOCK TABLES NameTable WRITE; alter table NameTable add column FullNameReverseOrder varchar(100) after FullName; COMMIT; UNLOCK TABLES;Untuk mengemas kini lajur yang baru ditambah Nama Akhir, Nama Tengah dan Nama Pertama, gunakan arahan berikut:
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) );Pilih,
select * from NameTable;Hasilnya
ID FullName FullNameReverseOrder age 1 ben thompson thompson ben 23 2 Martin Luther King King Luther Martin 23Sekarang, jika anda mahu proses ini berlaku secara automatik, pertimbangkan untuk mencipta pencetus.
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;Masukkan nilai ujian
insert into NameTable (ID, FullName, age) values (3, 'Arthur Thompson', 23); select * from NameTable;Hasilnya
ID FullName FullNameReverseOrder age 1 ben thompson thompson ben 23 2 Martin Luther King King Luther Martin 23 3 Arthur Thompson Thompson Arthur 23