MySQL: Selecting rows ordered by word count

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 12:19:57

问题


How can I order my query by word count? Is it possible?

I have some rows in table, with text fields. I want to order them by word count of these text fields.

Second problem is, that I need to select only these rows, which have for example minimum 10 words, or maximum 20.


回答1:


Well, this will not perform very well since string calculations need to be performed for all rows:

You can count number of words in a MySQL column like so: SELECT SUM( LENGTH(name) - LENGTH(REPLACE(name, ' ', ''))+1) FROM table (provided that words are defined as "whatever-delimited-by-a-whitespace")

Now, add this to your query:

SELECT
    <fields>
FROM
    <table>
WHERE
    <condition>
ORDER BY SUM(LENGTH(<fieldWithWords>) - LENGTH(REPLACE(<fieldWithWords>, ' ', '')) + 1)

Or, add it to the condition:

SELECT
    <fields>
FROM
    <table>
WHERE
    SUM(LENGTH(<fieldWithWords>) - LENGTH(REPLACE(<fieldWithWords>, ' ', '')) + 1) BETWEEN 10 AND 20
ORDER BY <something>



回答2:


Maybe something like this:

SELECT Field1, SUM( LENGTH(Field2) - LENGTH(REPLACE(Field2, ' ', ''))+1)
 AS cnt
FROM tablename
GROUP BY Field1
ORDER BY cnt

Field2 is the string field in which you'd like to count words.



来源:https://stackoverflow.com/questions/6516648/mysql-selecting-rows-ordered-by-word-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!