为了使其理解,我们使用了来自名为“ customerdetail”的表中的以下数据。
mysql> Select * from Customerdetail; +----------------------+----------------------+----------+---------------------+ | Name | FName | Address | Emailid | +----------------------+----------------------+----------+---------------------+ | Advik Jhamb | Lovkesh Jhamb | Mumbai | Advik@gmail.com | | Chirag Jai Patil | Raman Jai Patil | Gujrat | chirahp@yahoo.com | | Devansh Singh Rajput | Kishore Singh Rajput | Rajastan | Devansh@Hotmail.com | | Mitul Kumar Sharma | Om Veer Sharma | Patiala | Mitul@gmail.com | +----------------------+----------------------+----------+---------------------+ 4 rows in set (0.00 sec)
现在,假设我们要将名称分为“ First_name”,“ Middle_Name”和“ Last_name”三部分,则可以在以下查询的帮助下完成-
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。