gpt4 book ai didi

php - 在mysql中搜索字数统计查询

转载 作者:行者123 更新时间:2023-11-29 05:29:52 27 4
gpt4 key购买 nike

我有下表。

CREATE TABLE IF NOT EXISTS `product`
(
`id` int(11) NOT NULL,
`name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`description` varchar(200) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `product` (`id`, `name`, `description`) VALUES
(1, 'Samsung', "this is samsung product description from samsung"),
(2, 'Mobile', "Samsung galaxy note2 from samsung store"),
(3, 'Smartphone', "Samsung");

现在我想查询产生如下结果的product表。

ID   Name       WordCount
1 Samsung 3
2 Mobile 2
3 Smartphone 1

我如何计算这个词在 MySQL 选择查询中的出现次数。

编辑

很抱歉没有阐明我的观点。

但它就在这里。

我想从所有行中搜索 单词Samsung 并且不仅从名称而且从描述中计算它的出现次数。

最佳答案

经过几个小时的谷歌搜索和调试,我终于解决了这个问题。

我结合使用了 char_length 和 replace 来完成这个任务。

我最终得到的结果如下。

select  *,(
(char_length(name) - char_length(replace(name,'sam',''))) +
(char_length(description) - char_length(replace(description,'sam','')))
) / char_length('sam') as SearchCount
from
product
order by
SearchCount desc

上面的查询是CASE SENSITIVE 但别担心我也用CASE-INSESITIVE 解决了它,请看下面的查询。

select  *,
(
(char_length(name) - char_length(replace(LOWER(name),LOWER('Sam'),''))) +
(char_length(description) -
char_length(replace(LOWER(description),LOWER('Sam'),'')))
) / char_length('sam') as SearchCount
from
product
order by
SearchCount desc

完成此查询后,我们需要做的就是添加 WHERE 子句以使其工作。

希望这也能帮助其他人。

感谢大家的帮助(所有回答删除评论的人。)

关于php - 在mysql中搜索字数统计查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15943685/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com