2011-01-19 30 views
2

全文樣的搜索我有一個非常簡單的查詢:任何方式來實現對InnoDB的

SELECT ... WHERE row LIKE '%some%' OR row LIKE '%search%' OR row LIKE '%string%' 

搜索some search string,但你可以看到,它會搜索每個單獨的字符串,它也是不好性能。

有什麼方法可以在InnoDB表上使用LIKE重新創建一個類似全文的搜索。當然,我知道我可以使用像Sphinx這樣的東西來實現這一點,但我正在尋找純粹的MySQL解決方案。

+0

innodb不支持全文搜索... – ajreal 2011-01-19 05:54:36

+3

非常感謝您對我的啓發,對您非常有幫助:) – steve 2011-01-19 06:00:02

回答

6

使用的MyISAM表的全文索引回例如您的InnoDB表:

構建系統使用innodb:

create table users (...) engine=innodb; 

create table forums (...) engine=innodb; 

create table threads 
(
forum_id smallint unsigned not null, 
thread_id int unsigned not null default 0, 
user_id int unsigned not null, 
subject varchar(255) not null, -- gonna want to search this... !! 
created_date datetime not null, 
next_reply_id int unsigned not null default 0, 
view_count int unsigned not null default 0, 
primary key (forum_id, thread_id) -- composite clustered PK index 
) 
engine=innodb; 

現在我們將使用全文檢索表來索引回我們的innodb表。您可以通過使用觸發器或夜間批處理更新等保持在這個表中的行

create table threads_ft 
(
forum_id smallint unsigned not null, 
thread_id int unsigned not null default 0, 
subject varchar(255) not null, 
fulltext (subject), -- fulltext index on subject 
primary key (forum_id, thread_id) -- composite non-clustered index 
) 
engine=myisam; 

最後你從你的PHP /應用程序調用搜索存儲過程:

drop procedure if exists ft_search_threads; 
delimiter # 

create procedure ft_search_threads 
(
in p_search varchar(255) 
) 
begin 

select 
t.*, 
f.title as forum_title, 
u.username, 
match(tft.subject) against (p_search in boolean mode) as rank 
from 
threads_ft tft 
inner join threads t on tft.forum_id = t.forum_id and tft.thread_id = t.thread_id 
inner join forums f on t.forum_id = f.forum_id 
inner join users u on t.user_id = u.user_id 
where 
match(tft.subject) against (p_search in boolean mode) 
order by 
rank desc 
limit 100; 

end; 

call ft_search_threads('+innodb +clustered +index'); 

希望這有助於: )

2

使用PHP構建查詢。這是一個可怕的黑客。一旦看到,它不可能是看不見的......

$words=dict($userQuery); 
$numwords = sizeof($words); 
$innerquery=""; 
for($i=0;$i<$numwords;$i++) { 
    $words[$i] = mysql_real_escape_string($words[$i]); 
    if($i>0) $innerquery .= " AND "; 
    $innerquery .= " 
     (
      field1 LIKE \"%$words[$i]%\" OR 
      field2 LIKE \"%$words[$i]%\" OR 
      field3 LIKE \"%$words[$i]%\" OR 
      field4 LIKE \"%$words[$i]%\" 
     ) 
    "; 
} 


SELECT fields FROM table WHERE $innerquery AND whatever; 

字典是一本字典功能

相關問題