2013-04-11 93 views
1

我有下表。在mysql中搜索字數查詢

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選擇查詢。

編輯

對不起,不清除我的觀點。

但是在這裏。

我想searchSamsung從所有的行,並計算它的出現不僅從名稱,也從描述也。

+0

http://stackoverflow.com/questions/748276/using-sql-to-determine-word-count的可能的複製-stats-of-text-field – 2013-04-11 08:11:24

+0

@JacobTomlinson請參閱我的編輯...請 – 2013-04-11 08:27:31

+0

我認爲'雅各布湯姆林森的參考是正確的。它可能不是完全相同的,但它指向了正確的方向。 ''正確的方法是處理數據庫以外的數據,因爲數據庫用於存儲,而不是處理......' – Ejaz 2013-04-11 08:34:34

回答

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條款,使其工作。

希望這會幫助其他人。

感謝您的幫助(所有誰回答,並刪除評論的人。)