Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a string in multiple fields of a table

Tags:

sql

php

mysql

I have a table User which has the fields (id, first_name, middle_name, last_name).

I want to write a query to find a user by his name. The name may be first name, middle name or last name.

$sql = "SELECT * FROM user 
        WHERE first_name like '%$name%' OR  
              middle_name like '%$name%' OR
              last_name like '%$name%'";

Is it efficient query? (Leave the security issue for the time being.)

like image 914
Mohammed H Avatar asked Oct 09 '22 05:10

Mohammed H


1 Answers

Alter table and add composite Fulltext index on First_name,second_name,last_name then use this query

select * 
from table_name 
where match (`First_name`,`second_name`,`last_name`) against('name')

It's pretty much faster then your query.

like image 199
Ankit Sharma Avatar answered Oct 11 '22 01:10

Ankit Sharma