Match .. against query and FULLTEXT search of MySQL table
MySQL provides search facility by using match .. and against query.
Here is the syntax
SELECT * FROM table_name where match ( column1, column2.. ) against ( 'keyword1 keyword2')
Adding Index to columns
Before using match against search query to MySQL table we have to index the columns. There are three types of Indexes
FullText Index can be applied to char, varchar and text columns.
We can add fulltext index while creating the table or we can use alter command to add fulltext index.
Changing the structure to add FULTEXT index
ALTER TABLE `sql_tutorial`.`student` ADD FULLTEXT `my_ind` (`name`)
Creating table with FULLTEXT Index
CREATE TABLE IF NOT EXISTS `student` (
`id` int(2) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL DEFAULT '',
`class` varchar(10) NOT NULL DEFAULT '',
`mark` int(3) NOT NULL DEFAULT '0',
`sex` varchar(6) NOT NULL DEFAULT 'male',
UNIQUE KEY `id` (`id`),
FULLTEXT KEY `my_ind` (`name`,`class`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=36 ;
To add FULLTEXT index your table type must be of MyISAM. Table type InnoDB doesn't not support FULLTEXT index. However MySQL version 5.6 onwards support for FULLTEXT index is available.
You will get message like this
The used table type doesn't support FULLTEXT indexes
Changing the structure to add FULLTEXT index
ALTER TABLE `sql_tutorial`.`plus2_file_php` ADD FULLTEXT `my_ind` (`title` ,`des`)
How to use Query
We can apply query to get the matching data. Here is the sql
SELECT * FROM `student` WHERE match(name) against('alex')
Sample script using match .. against
We have developed a simple script where SQL is developed using search string.
First we will show a search box. On Submit of the form the string is collected and sql is developed .