全文索引
官网说明:全文索引
只能在text,char , varchar类型字段上创建全文索引;
创建:
CREATE TABLE `article` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(200) DEFAULT NULL,
`content` text, PRIMARY KEY (`id`), FULLTEXT KEY `fulltext_article` (`title`,`content`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
或者:
ALTER TABLE article ADD FULLTEXT INDEX fulltext_article(title,content);
查询:
SELECT COUNT(*) FROM articles WHERE MATCH (title,body) AGAINST ('database' IN NATURAL LANGUAGE MODE);
SELECT COUNT(IF(MATCH (title,body) AGAINST ('database' IN NATURAL LANGUAGE MODE), 1, NULL)) AS count FROM articles;
检索模式:
1、in natural language mode 适用于单表的查询,把查询字符串作为一个短语,如果有不少于50%的行匹配,则认为没有匹配的。
2、in boolean mode
SELECT id, title, body, MATCH (title,body) AGAINST ('database' IN BOOLEAN MODE) AS score FROM articles ORDER BY score DESC;
The following examples demonstrate some search strings that use boolean full-text operators: 'apple banana' Find rows that contain at least one of the two words. '+apple +juice' Find rows that contain both words. '+apple macintosh' Find rows that contain the word “apple”, but rank rows higher if they also contain “macintosh”. '+apple -macintosh' Find rows that contain the word “apple” but not “macintosh”. '+apple ~macintosh' Find rows that contain the word “apple”, but if the row also contains the word “macintosh”, rate it lower than if row does not. This is “softer” than a search for '+apple -macintosh', for which the presence of “macintosh” causes the row not to be returned at all. '+apple +(>turnover Find rows that contain the words “apple” and “turnover”, or “apple” and “strudel” (in any order), but rank “apple turnover” higher than “apple strudel”. 'apple*' Find rows that contain words such as “apple”, “apples”, “applesauce”, or “applet”. '"some words"' Find rows that contain the exact phrase “some words” (for example, rows that contain “some words of wisdom” but not “some noise words”). Note that the " characters that enclose the phrase are operator characters that delimit the phrase. They are not the quotation marks that enclose the search string itself. |