1

我有下表。

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选择查询中计算这个词的出现次数。

编辑

很抱歉没有澄清我的观点。

但在这里。

我想从所有行中search说出单词Samsung,并不仅从名称而且从描述中计算它的出现。

4

1 回答 1

3

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

我使用了 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-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子句以使其工作。

希望这对其他人也有帮助。

感谢您的帮助(所有回答并删除和评论的人。)

于 2013-04-11T11:59:45.433 回答