如何使用 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 | Rajasthan | [email protected] | | Mitul Kumar Sharma | Om Veer Sharma | Patiala | [email protected] | +----------------------+----------------------+-----------+---------------------+ 4 rows in set (0.00 sec)
现在,假设如果我们想要将名称分为两个部分,“First_name”和“Last_name”,则可以使用以下查询来完成−
mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ' ', 1), ' ', -1) AS First_Name, TRIM( SUBSTR(Name, LOCATE(' ', Name)) ) AS Last_Name FROM Customerdetail; +------------+--------------+ | First_Name | Last_Name | +------------+--------------+ | Advik | Jhamb | | Chirag | Jai Patil | | Devansh | Singh Rajput | | Mitul | Kumar Sharma | +------------+--------------+ 4 rows in set (0.00 sec)
从上述查询的结果集中,很明显名称已分为两个部分。它将中间名视为姓氏的一部分。
广告