MySQL 查询,用于计算整行中的空格或单词


mysql query to count white spaces or words from entire row

在我的数据库中,有一个表的名称为表A.表的结构在这里给出

id      from     message
1       23       hi how are you
2       65       hey whats going on
3       74       enjoying the vacation with family
4       23       here in Australia its chilly season
5       74       hey sam whats the plan for tomorrow

请参阅 id 是自动递增的。从列表示哪个用户正在发送消息,消息列由消息组成。 我想知道哪些用户发送了多少个单词,所以我必须首先计算行中的单词,然后我必须搜索整个列并找到重复的地方并添加该特定 user.in 的单词 在我的示例中,您可以看到 23 和 74 中的两个地方即将到来。我希望我的输出为

    from       nos
    23         10
    65         4 
    74         12

在这里你可以看到 23 是两行来的,所以我添加了两行的单词数,就像 74 也来了两行。

您可以通过此查询计算单词-

Select length('string')-length(replace('string',' ',''))+1;

对于您的桌子,您可以这样做

Select *,(length(message)-length(replace(message,' ',''))+1) from table_name

这将显示每个味精的字数。

为了您想要的结果,请尝试以下-

Select `from`, sum((length(message)-length(replace(message,' ',''))+1)) as nos from table_name group by `from`

假设单词由单个空格分隔,您可以使用:

SUM( LENGTH(message) - LENGTH(REPLACE(message, ' ', ''))+1)

以获得字数统计。由于您希望对来自每个用户的所有消息求和,因此需要按用户(从列)分组。最后你应该有这样的东西:

select `from`, SUM( LENGTH(message) - LENGTH(REPLACE(message, ' ', ''))+1) as nos
from tableA
group by `from`
SELECT from, SUM(LENGTH(message) - LENGTH(REPLACE(TRIM(message), ' ', ''))+1) FROM my_table GROUP BY from;