如何使用 MySQL SUBSTRING_INDEX() 函数将姓名字符串分成三部分?
为了帮助大家理解,我们使用名为“customerdetail”的表中的以下数据。
mysql> Select * from Customerdetail; +----------------------+----------------------+----------+---------------------+ | Name | FName | Address | Emailid | +----------------------+----------------------+----------+---------------------+ | Advik Jhamb | Lovkesh Jhamb | Mumbai | [email protected] | | Chirag Jai Patil | Raman Jai Patil | Gujrat | [email protected] | | Devansh Singh Rajput | Kishore Singh Rajput | Rajastan | [email protected] | | Mitul Kumar Sharma | Om Veer Sharma | Patiala | [email protected] | +----------------------+----------------------+----------+---------------------+ 4 rows in set (0.00 sec)
现在,假设我们要将姓名分成三部分,“名”、“中间名和“姓”,可以使用以下查询来完成−
mysql> SELECT Name, SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 1), ' ', -1) AS First_Name, If( length(Name) - length(replace(Name, ' ', ''))>1, SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 2), ' ', -1) ,NULL)AS Middle_Name, SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 3), ' ', -1) AS Last_Name, Address FROM customerdetail; +----------------------+------------+-------------+-----------+----------+ | Name | First_Name | Middle_Name | Last_Name | Address | +----------------------+------------+-------------+-----------+----------+ | Advik Jhamb | Advik | NULL | Jhamb | Mumbai | | Chirag Jai Patil | Chirag | Jai | Patil | Gujrat | | Devansh Singh Rajput | Devansh | Singh | Rajput | Rajastan | | Mitul Kumar Sharma | Mitul | Kumar | Sharma | Patiala | +----------------------+------------+-------------+-----------+----------+ 4 rows in set (0.00 sec)
从上面查询返回的结果集中,很明显姓名已经分成三部分。如果姓名不包含中间名,则它会将中间名视为 NULL。
广告