Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search string by exact word in Mysql

Tags:

php

mysql

I have a system that searches for company. I want that when a user searches for "Demo", all records that have "Demo" will be returned, like "The Demo", "Demo Inc.", etc. I don't want those records like "Democratic", "Demolition", etc. I think you get my point.

Right now, my working query looks something like this:

select * from table where company LIKE "Demo%"

But that really doesn't hit my requirement. I also tried this one:

select * from table where company RLIKE "[[:<:]]demo[[:>:]]"

The only problem on that one is that it eliminates the possibility of index on my company field. So it searches really slow. I have over a million records right now. Any idea how to do it? If it can't be done in mysql, any idea if it's possible in PHP? Thanks!

like image 533
user3360031 Avatar asked Sep 30 '14 11:09

user3360031


People also ask

How do I find a specific word in a MySQL database?

MySQL Workbench There is a Schemas tab on the side menu bar, click on the Schemas tab, then double click on a database to select the database you want to search. Then go to menu Database - Search Data, and enter the text you are searching for, click on Start Search.

How do I find a word in a string MySQL?

MySQL LOCATE() Function The LOCATE() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0. This function performs a case-insensitive search. Note: This function is equal to the POSITION() function.

Where is exact match in MySQL?

Answer: MySQL LIKE Operator works with 2 wildcard characters in MySQL to achieve different ways of pattern matching. These are: % – This would match any number of characters (including zero) _ – This would match exactly one character.

How do I select a part of a string in MySQL?

SUBSTRING() function in MySQL function in MySQL is used to derive substring from any given string . It extracts a string with a specified length, starting from a given location in an input string.


2 Answers

Create an Full text index, and then you can search more easy.

ALTER TABLE table ADD FULLTEXT INDEX fulltext_index;


SELECT * FROM table WHERE MATCH (company) AGAINST ('+Demo' IN BOOLEAN MODE); 

dev.mysql.com/doc/refman/5.6/en/fulltext-search.html

like image 89
faster2b Avatar answered Oct 17 '22 13:10

faster2b


You can use REGEXP and the [[:<:]] and [[:>:]] word boundary markers:

SELECT
    *
FROM
    `table`
WHERE
    company REGEXP '[[:<:]]Demo[[:>:]]';

Another Solution

SELECT
    *
FROM
    `table`
WHERE
    company REGEXP '(^|[[:space:]])Demo([[:space:]]|$)';

SQL Fiddle Demo

like image 31
Faisal Avatar answered Oct 17 '22 12:10

Faisal