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

后端 未结 8 1688
旧巷少年郎
旧巷少年郎 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 20:07

    Build on Narnian's answer, here's one that works with two fields (a.product,a.descr) and where "..." is added when the string is truncated. a.descr can be empty as well.

      IF (
    CHARACTER_LENGTH(
      IF(
        a.descr = '',
        a.product,
        CONCAT_WS(' - ',a.product,a.descr)
      )
    )>35,
    IF(
      a.descr = '',
      CONCAT(
        REVERSE(SUBSTRING(REVERSE( SUBSTRING(a.product, 1, 35)), locate(' ', REVERSE( SUBSTRING(a.product, 1, 35))), 35)),
        '...'
      ),
      CONCAT(
        REVERSE(SUBSTRING(REVERSE( SUBSTRING(CONCAT_WS(' - ',a.product,a.descr), 1, 35)), locate(' ', REVERSE( SUBSTRING(CONCAT_WS(' - ',a.product,a.descr), 1, 35))), 35)),
        '...'
      )
    ),
    CONCAT_WS(' - ',a.product,a.descr)
    )
    

    I needed something like this so that's why i added it. Might help someone else.

提交回复
热议问题