简体   繁体   English

MySQL删除列中n个单词后的所有内容

[英]MySQL remove everything after n words in column

I have a table with over 5000 entries, and basically I want to replace the texts with excerpts. 我的桌子有5000多个条目,基本上我想用摘录替换文本。 So the column 'text' has between 1000 and 2000 words, most of the time. 因此,“文本”列通常在1000到2000个单词之间。 I want every cell to be cut after 80 words. 我希望每个单元格在80个单词后被删减。 Additionally it would be nice to add something like 'Read more...' after the 80 words. 另外,最好在80个单词之后添加“阅读更多...”之类的内容。 Is it possible with a MySQL Query? MySQL查询可以吗?

This is bad idea to do that from MySQL level. 从MySQL级别执行此操作不是一个好主意。 This is about the VIEW Layer, so should be programmed in the place which read the data from the database and presents them. 这是关于VIEW层的,因此应该在从数据库读取数据并将其呈现的地方进行编程。 In PHP, it can be done with 在PHP中,可以使用

function cutStringAfterWords($phrase,$max_words){
    $phrase_array = explode(' ',$phrase);
    if(count($phrase_array) > $max_words && $max_words > 0)
        $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';
    return $phrase;
}

echo cutStringAfterWords($largeText,80).' Read more...';

, but I believe most of the languages have their equivalents. ,但我相信大多数语言都有它们的对等语言。

Edit: made an example to cut after 80 words. 编辑:举了一个例子,减少了80个字。 you can simply replace 3 dots within function to place Read more always, or remove 3 dots in function, and manually add 'Read More...' string after every truncated text 您可以简单地替换函数中的3个点以始终读取更多,或删除函数中的3个点,并在每个截断的文本之后手动添加“ Read More ...”字符串

You can try with regex. 您可以尝试使用正则表达式。

select REGEXP_SUBSTR(your_column_name,'(.+?\\s+|.+?){1,80}')
from your_table_name

There's nice MySQL string function SUBSTRING_INDEX which you can use like this to get the result you want: 有一个不错的MySQL字符串函数SUBSTRING_INDEX ,您可以像这样使用它来获取所需的结果:

UPDATE your_table SET your_text_field = (SELECT SUBSTRING_INDEX(your_text_field, ' ', 80) FROM your_table WHERE text_id = some_id) WHERE text_id = some_id; 更新your_table SET your_text_field =(从your_table中选择SUBSTRING_INDEX(your_text_field,'',80)WHERE text_id = some_id)WHERE text_id = some_id;

To add 'Read More..' you can use MySQL CONCAT . 要添加“阅读更多..”,可以使用MySQL CONCAT

Also, I would suggest backing up your table before you start experimenting. 另外,我建议您在开始实验之前备份表。

execute below query to update all records with first 80 characters 执行以下查询以更新前80个字符的所有记录

update your_table_name set column_name=SUBSTRING_INDEX(column_name, ' ', 80)

Updated with SUBSTRING_INDEX since you need words 由于您需要输入文字,因此已用SUBSTRING_INDEX更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM