简体   繁体   English

按MySQL字段中的单词数排序

[英]Sort by the number of words in a MySQL field

I would like to sort a result from a MySQL query by the number of words in a specified column. 我想根据指定列中的单词数对MySQL查询的结果进行排序。

Something like this: 像这样的东西:

SELECT bar FROM foo ORDER BY WordCountFunction(bar)

Is it possible? 可能吗?

As far as I know, there is no word count function in MySQL, but you can count the number of spaces and add one if your data is formatted properly (space separator for words, no spaces at beginning/end of entry). 据我所知,MySQL中没有字数统计功能,但如果数据格式正确,可以计算空格数并添加一个空格(单词空格分隔符,条目开头/结尾没有空格)。

Here is the query listing longest words first: 这是查询最长单词的查询:

SELECT bar FROM foo ORDER BY (LENGTH(bar) - LENGTH(REPLACE(bar, ' ', ''))+1) DESC

使用此方法计算列中的单词数,您的查询将如下所示:

SELECT bar FROM foo ORDER BY (LENGTH(bar) - LENGTH(REPLACE(bar, ' ', ''))+1) DESC

Yes, sort of. 是的,有点。 It won't be 100% accurate though: 但它不会100%准确:

SELECT SUM(LENGTH(bar) - LENGTH(REPLACE(bar, ' ', ''))+1) as count
FROM table
ORDER BY count DESC

But this assumes the words are separated by a space ' ' and doesn't account for punctuation. 但这假设单词用空格' '分隔,并不考虑标点符号。 You can always replace it with another char and it doesn't account for double spaces or other chars either. 您总是可以用另一个char替换它,它也不会占用双倍空格或其他字符。

For complete accuracy, you could always pull the result out and word-count in your language of choice - where accurate word-count function do exist! 为了获得完全的准确性,您可以随时使用您选择的语言提取结果并计算字数 - 确实存在准确的字数统计功能!

Hope this helps. 希望这可以帮助。

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

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