[英]How to separate a comma separated name field in MySQL in to first name, middle name, last name and fullname?
I have a NAME
column and the data is stored like this in a MySql database: 我有一个NAME
列,数据像这样存储在MySql数据库中:
Doe,John P 道恩,约翰·P
I would like to break it out into FNAME
LNAME
MNAME
and FULLNAME
. 我想将其分为FNAME
LNAME
MNAME
和FULLNAME
。
If I don't want to tamper with the SQL table, should I create a view? 如果我不想篡改SQL表,是否应该创建视图?
I know how to fix it in PHP with a function but I would rather the processing be done on the database server than the application server. 我知道如何使用函数在PHP中修复它,但是我宁愿在数据库服务器上而不是在应用程序服务器上进行处理。
This is what I have so far. 到目前为止,这就是我所拥有的。 I thinking I need a compound query or something similar. 我想我需要一个复合查询或类似的东西。
SELECT Name
, SUBSTRING_INDEX(Name,',',-1) As FNAME
, SUBSTRING_INDEX(Name,',',1) As LNAME
, SUBSTRING_INDEX(Name,' ',1) As MNAME
FROM people;
I'm having trouble grabbing the middle name and doing what I think should be CONCAT
function to get FULLNAME
. 我在获取中间名和执行我认为应该是CONCAT
函数来获取FULLNAME
遇到麻烦。
It would be great if there was a way (maybe a conditional) to handle names in the database that didn't have middle names. 如果有一种方法(可能是有条件的)来处理数据库中没有中间名的名称,那将是很好的。 (ie DOE,JOHN). (即DOE,JOHN)。
A view is a fine way to get the results you want for future queries. 视图是一种获得所需的未来查询结果的好方法。 The defining query would be: 定义查询将是:
SELECT Name, SUBSTRING_INDEX(SUBSTRING_INDEX(Name, ',', -1), ' ', 1) As FNAME,
SUBSTRING_INDEX(Name, ',', 1) As LNAME,
SUBSTRING_INDEX(Name, ' ', -1) As MNAME
FROM people;
This will work assuming that the format is exactly correct as you describe it in the table. 假设该格式与您在表中描述的格式完全正确,那么它将起作用。 Small changes -- such as no middle name or a space after the comma -- would make the syntax more complicated. 较小的更改(例如没有中间名或逗号后有空格)会使语法更加复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.