MySQL truncate text with ellipsis

前端 未结 6 488
小鲜肉
小鲜肉 2021-01-04 01:14

Suppose I have a MySQL table of one column: \"Message\". It is of type TEXT. I now want to query all rows, but the text can be large (not extremely large but large) and I on

6条回答
  •  遥遥无期
    2021-01-04 01:48

    My approach:

    • Let x be the maximum number of characters to display (therefore x + 3 dots will be the longest string displayed)
    • You always want LEFT(field,x)
    • If LENGTH(field) > x + 3, append 3 dots
    • Otherwise if LENGTH(field) > x, append the remainder of field
    SELECT CONCAT(
        LEFT(field,x),
        IF(LENGTH(field) > x+3,
           '...',
            IF(LENGTH(field) > x,
                MID(field,x+1,LENGTH(field)),
                ''
            )
        )
    ) FROM table
    

提交回复
热议问题