【发布时间】:2012-03-29 06:41:28
【问题描述】:
我在一个表中有 2 列,我想大致报告总字数。 是否可以运行 MySQL 查询并找出一列中的总字数。
它基本上是由一个空格或多个空格分隔的任何文本。 不需要 100% 准确,因为它只是一个一般指南。
这可能吗?
【问题讨论】:
标签: mysql
我在一个表中有 2 列,我想大致报告总字数。 是否可以运行 MySQL 查询并找出一列中的总字数。
它基本上是由一个空格或多个空格分隔的任何文本。 不需要 100% 准确,因为它只是一个一般指南。
这可能吗?
【问题讨论】:
标签: mysql
试试这样的:
SELECT COUNT(LENGTH(column) - LENGTH(REPLACE(column, ' ', '')) + 1)
FROM table
这将计算列中的字符数,并减去列中删除所有空格的字符数。由此你知道你的行中有多少个空格,从而知道有多少个单词(大致是因为你也可以输入一个双空格,这将算作两个单词,但你说你大致想要它,所以这就足够了)。
【讨论】:
Count 只是为您提供找到的行数。您需要改用 SUM。
SELECT SUM(LENGTH(column) - LENGTH(REPLACE(column, ' ', '')) + 1) FROM table
【讨论】:
不那么粗略的计数:
SELECT LENGTH(column) - LENGTH(REPLACE(column, SPACE(1), ''))
FROM
( SELECT CONCAT(TRIM(column), SPACE(1)) AS column
FROM
( SELECT REPLACE(column, SPACE(2), SPACE(1)) AS column
FROM
( SELECT REPLACE(column, SPACE(3), SPACE(1)) AS column
FROM
( SELECT REPLACE(column, SPACE(5), SPACE(1)) AS column
FROM
( SELECT REPLACE(column, SPACE(9), SPACE(1)) AS column
FROM
( SELECT REPLACE(column, SPACE(17), SPACE(1)) AS column
FROM
( SELECT REPLACE(column, SPACE(33), SPACE(1)) AS column
FROM tableX
) AS x
) AS x
) AS x
) AS x
) AS x
) AS x
) AS x
【讨论】:
我自己在寻找答案时偶然发现了这篇文章,说实话我已经在这里测试了所有答案,最接近的是@fikre 的答案。但是,我担心单词之间有前导空格和/或额外空格的数据(在我的测试期间,尾随空格似乎对 fikre 的查询没有影响)。所以,我正在寻找一种方法来识别单词之间的任何空格并删除它们。虽然我找到了一些使用高级功能的答案(这超出了我的技能范围),但我确实找到了一种非常简单的方法。
tl;dr > @fikre 的答案是唯一对我有用的答案,但我做了一些小调整以确保获得最准确的字数。
Query 1 -- This will return 5 "Word Count"
SELECT SUM(LENGTH(input) - LENGTH(REPLACE(input, ' ', '')) + 1) AS "Word Count" FROM
(SELECT TRIM(REPLACE(REPLACE(REPLACE(input,' ','<>'),'><',''),'<>',' ')) AS input
FROM (SELECT ' too late to the party ' AS input) i) r;
Query 2 -- This will return 13 "Word Count"
SELECT SUM(LENGTH(input) - LENGTH(REPLACE(input, ' ', '')) + 1) AS "Word Count"
FROM (SELECT ' too late to the party ' AS input) i;
-- breakdown ' too late to the party '
1 leading space= 1 word count
2 spaces after the first space from the word 'too'= 2 word count
1 space after the first space from the word 'late'= 1 word count
4 spaces after the first space from the word 'the'= 4 word count
trailing space(s) wasn't counted at all.
Total spaces > 1+2+1+4=8 + 5 word count = 13
因此,基本上,如果数据行之间甚至包含一百万个空格(免责声明:假设。我只测试了 336,896 个空格),Query 1 仍将返回字数=5。
注意:中间部分REPLACE(REPLACE(REPLACE(input,' ','<>'),'><',''),'<>',' ')我取自这个答案https://stackoverflow.com/a/55476224/10910692
【讨论】: