2011-05-09 114 views
2

的我有以下表中的行:SQLite的全文搜索:查找countains任何關鍵字

-- table to keep articles titles 
CREATE TABLE articles(id, title); 
insert into articles (id,title) values (1,'sqlite example'); 
insert into articles (id,title) values (2,'sqlite query '); 
insert into articles (id,title) values (3,'erlang example '); 
insert into articles (id,title) values (3,'erlang otp '); 

-- table to keep keywords that we would like to search. 
create table keywords(id,keyword); 
insert into keywords (id,keyword) values (1,'sqlite'); 
insert into keywords (id,keyword) values (2,'otp'); 


-- full text search table - copy of articles. 

create virtual table articles_fts using fts4 (id,name); 

-- populate table with articles titles. 
insert into articles_fts(id,name) select id,title from articles; 

現在我想找到任何包含指定關鍵字的所有文章

查詢,如:

select * from articles_fts 
    where name match (select keyword from keywords); 

僅返回它sqlite的(第一關鍵字)冠軍,所以關鍵字表格的其他條目將被忽略。

問題: 我怎麼能找到包含任何指定關鍵字的所有文章? 謝謝。

回答

2

使用

select * 
    from articles_fts 
WHERE articles_fts MATCH (select group_concat(keyword, ' OR ') 
           from keywords 
          group by 'x') 

group_concat功能聚合所有的關鍵字用逗號。如果你用OR替換逗號,它應該產生一個很好的FTS查詢。

有關OR關鍵字和reference for aggregate functions的另請參見the full text search feature reference的第3節。

+0

看起來不起作用:'錯誤:在GROUP BY子句中不允許使用聚合函數',如果我沒有使用'GROUP BY 1'',沒有錯誤,但查詢返回沒有行:( – 2011-05-09 08:09:56

+0

@Anton Prokoiev:我使用1作爲常量,並忘記它被解釋爲列參考,嘗試用'x'來代替 – Benoit 2011-05-09 09:22:28

+1

謝謝你的工作。唯一的一個說法:你的查詢應該是這樣的: '從articles_fts中選擇articles_fts MATCH(從關鍵字組中選擇group_concat(關鍵字,'OR')'x');'。**所以'OR'應該是UPPER CASE **在其他情況下它不作爲關鍵字:) – 2011-05-09 10:28:52