String truncate on length, but no chopping up of words allowed

后端 未结 8 1687
旧巷少年郎
旧巷少年郎 2020-12-15 19:33

I want to limit a string field length in MYSQL on a certain length, but I don\'t want any chopping up of words to occur.

When I do:

SELECT SUBSTRING(         


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 19:57

    Let @str be your string and @len the initial position to cut at. Then the necessary steps could be:

    1. Take the leftmost @len characters of @str.

    2. Reverse the substring.

    3. Find the position of the first space in the reversed substring.

    4. Subtract 1 from the position. But if no space was found, let the position remain 0.

    5. Subtract the found position from @len and call it cutpos.

    6. Take the first (leftmost) cutpos characters of @str as str1, take all the other characters (starting from cutpos+1) as str2.

    SELECT
      LEFT(str, cutpos) AS str1,
      SUBSTRING(str, cutpos + 1) AS str2
    FROM (
      SELECT
        @str AS str,
        @len - IFNULL(NULLIF(LOCATE(' ', REVERSE(LEFT(@str, @len))), 0) - 1, 0) AS cutpos
    ) s
    

提交回复
热议问题