简体   繁体   中英

How to change the structure of a name field in mysql

I have the following problem.

My table, say tab1, has name column as follows "LastName, FirstName". I want to make it so that the column becomes "FirstName LastName".

Any ideas on how this is to be done? Note that there is no comma present, but i guess that can be easily removed once I figure out how to actually flip the first and the last names.

Any help would be appreciated.

Thanks.

  • It would be better to split the name column into two fields, FirstName and LastName , so that you can format them in any way you want, and still sort on last name.
  • Use substring and substring_index to find comma's and split on them. See the manual .

replace @NAME with your real value:

SELECT TRIM(SUBSTR(@NAME, LOCATE(",", @NAME) + 1)) AS prename, TRIM(SUBSTR(@NAME, 1, LOCATE(",", @NAME) - 1)) AS surename

This will extract the prename and surename part, now you can insert/modify the data as you want to.

Not an answer to your question, but I would not do this under any circumstances. You will lose any chance to reliably tell apart last name and first name. Consider the following names:

Bridget St John
Boutros Boutros Ghali
Karl-Theodor Maria Nikolaus Freiherr von und zu Guttenberg

I recommend keeping separate "last name" and "first name" columns. You can concatenate them as you please when you do your output.

UPDATE table SET name2=CONCAT (TRIM(SUBSTR(name, LOCATE(",", name) + 1)), ' ', TRIM(SUBSTR(name, 1, LOCATE(",", name) - 1)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM