MySQL - finding the exact word from a string

I want to find the exact word from a string, for example

id  Description
1   This is nice pen looking good
2   This is nice pendrive looking good

Search string :pen

My current request

SELECT * FROM `table` WHERE Description like '%pen%';

Above the query, return both records, but I want only the first record. Because the word pen exactly matches my search bar.

Expected Result

1   This is nice pen looking good

Demo

+4
source share
4 answers

Try using regular expressions:

SELECT 
    *
FROM
    `table`
WHERE
    Description regexp '(^|[[:space:]])pen([[:space:]]|$)';

Demo

Or using word boundaries :

SELECT 
    *
FROM
    `table`
WHERE
    Description regexp '[[:<:]]pen[[:>:]]';
+5
source

You can use REGEXPboth [[:<:]]and [[:>:]]word boundary labels:

SELECT
    *
FROM
    `table`
WHERE
    Description REGEXP '[[:<:]]pen[[:>:]]';

SQL Fiddle Demo

+2
source

,

$query="SELECT * FROM table_name WHERE MATCH (column_name) AGAINST 
  ('search_word' IN NATURAL LANGUAGE MODE)" ;

,

0

,

SELECT * FROM 'table' WHERE Description ='pen';
0
source

Source: https://habr.com/ru/post/1668783/


All Articles