Select rows containing a string in a specific column with MATCH and AGAINST in MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1833
     (
     Name varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

Alter table −

Mysql> alter table DemoTable1833 ADD FULLTEXT(Name);
Query OK, 0 rows affected, 1 warning (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 1

Insert some records in the table using insert command −

mysql> insert into DemoTable1833 values('John Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1833 values('Adam Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1833 values('Chris Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1833 values('John Smith');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1833;

This will produce the following output −

+-------------+
| Name        |
+-------------+
| John Doe    |
| Adam Smith  |
| Chris Brown |
| John Smith  |
+-------------+
4 rows in set (0.00 sec)

Here is the query to select rows containing a string in a specific column

mysql> select * from DemoTable1833 where MATCH(Name) AGAINST('+John Smith+') ;

This will produce the following output −

+------------+
| Name       |
+------------+
| John Smith |
| John Doe   |
| Adam Smith |
+------------+
3 rows in set (0.00 sec)
raja
Published on 24-Dec-2019 07:49:58
Advertisements