[英]Query to count the distinct words of all values in a column
我有一个 mysql 表“post”:
id Post
-----------------------------
1 Post Testing
2 Post Checking
3 My First Post
4 My first Post Check
我需要计算Post
列的所有值中不同单词的数量。
有没有办法使用单个查询获得以下结果?
post count
------------------
Post 4
Testing 1
checking 1
My 2
first 2
check 1
不是很容易。 如果您知道最大单词数,那么您可以执行以下操作:
select substring_index(substring_index(p.post, ' ', n.n), ' ', -1) as word,
count(*)
from post p join
(select 1 as n union all select 2 union all select 3 union all select 4
) n
on length(p.post) - length(replace(p.post, ' ', '')) < n.n
group by word;
请注意,这仅适用于单词由单个空格分隔的情况。 如果您有一个包含所有可能单词的单独字典,您也可以使用它,例如:
select d.word, count(p.id)
from dictionary d left join
posts p
on concat(' ', p.post, ' ') like concat(' %', d.word, ' %')
group by d.word
首先将 FULLTEXT 索引添加到您的列中,例如:
CREATE FULLTEXT INDEX ft_post
ON post(Post);
然后使用优化表将索引刷新到磁盘:
SET GLOBAL innodb_optimize_fulltext_only=ON;
OPTIMIZE TABLE post;
SET GLOBAL innodb_optimize_fulltext_only=OFF;
设置辅助表:
SET GLOBAL innodb_ft_aux_table = '{yourDb}/post';
现在您可以简单地选择字数和字数,例如:
SELECT word, doc_count FROM INFORMATION_SCHEMA.INNODB_FT_INDEX_TABLE;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.