Mysql extract first letter of each word in a specific column

后端 未结 5 1724
予麋鹿
予麋鹿 2021-01-16 02:36

I want to create an acronym column in a table. I want to be grab the first letter of each word from a \'name\' column, capitalize it, then concatenate all into an \'acronym\

5条回答
  •  失恋的感觉
    2021-01-16 03:28

    I know this is a little late to the game, but I wanted to offer up a non-function way of doing this for those of you creating a view or a .sql file for periodic use:

    SELECT
        @spaces:= length(fi.FacilityName) - length(replace(fi.FacilityName,' ','')) as spaces,
        concat(left(fi.FacilityName,1),
            if(@spaces > 0, substring(fi.FacilityName,@pos:=locate(' ',fi.FacilityName)+1,1),''),
            if(@spaces > 1, substring(fi.FacilityName,@pos:=locate(' ',fi.FacilityName, @pos)+1,1),''),
            if(@spaces > 2, substring(fi.FacilityName,@pos:=locate(' ',fi.FacilityName,@pos)+1,1),''),
            if(@spaces > 3, substring(fi.FacilityName,@pos:=locate(' ',fi.FacilityName,@pos)+1,1),''),
            if(@spaces > 4, substring(fi.FacilityName,@pos:=locate(' ',fi.FacilityName,@pos)+1,1),'')) as initials
    from facilityInfo fi
    

    It's two steps, and you have to include a conditional substring() line for every word you anticipate being in the string, but that is just a copy, paste, and increment of the comparison value for @spaces. My requirements for doing this may be a little looser than some, however. Regardless, it works and causes no noticeable speed issues.

提交回复
热议问题