MYSQL修剪字符串没有切断midword

时间:2013-08-15 07:16:40

标签: mysql concatenation trim

我有一个带描述字段的数据库。我希望能够仅返回该字段的一部分(150个字符),但是我不想将它们从字中删除。 (比如... ...

有关如何实现这一目标的任何想法?

目前我有:

SELECT  e.*, e.id as event_id, CONCAT(SUBSTRING(e.description,1, 100),'...') AS short_description, FROM events e

由于

2 个答案:

答案 0 :(得分:0)

编写一个操作字符串的数据库函数,如果太长则将其删除并添加“...”。

从SELECT语句中调用函数(假设您调用函数LIMIT_TEXT):

SELECT  e.*, e.id as event_id, LIMIT_TEXT(e.description, 100, '...') AS short_description, FROM events e

答案 1 :(得分:0)

你可以使用这样的查询:

SELECT
  e.*, e.id as event_id,
  CASE WHEN SUBSTRING(e.description, 101, 1)=' '
            OR CHAR_LENGTH(e.description)<=100
  THEN
    TRIM(SUBSTRING(e.description, 1, 100))
  ELSE
    SUBSTRING(e.description, 1,
              100-LOCATE(' ', REVERSE(SUBSTRING(e.description, 1, 100))))
  END as short_description
FROM
  events e

请参阅小提琴here