Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT MySQL field that contains a substring [duplicate]

Tags:

string

sql

mysql

Using LIKE is very common in MySQL. We use it like this: WHERE field LIKE '%substring%'. Where we have a substring and field has full string. But what I need is something opposite. I have substrings in field. So, I want that row which contains a substring of my string. Suppose the table is:

----+-------------------
 id | keyword
----+-------------------
  1 | admission
----+-------------------
  2 | head of the dept
----+-------------------

and I have a string from user: Tell me about admission info. I need such a MySQL query that returns admission as this is a substring of user string. Something like:

SELECT keyword FROM table WHERE (keyword is a substring of 'Tell me about admission info')

thanks in advance.

like image 235
A. K. M. Tariqul Islam Avatar asked Sep 15 '13 07:09

A. K. M. Tariqul Islam


People also ask

How do you check if a substring is present in a string in 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.

How do I find duplicate values in two columns in MySQL?

Find Duplicate Row values in Multiple ColumnsSELECT col1, col2,..., COUNT(*) FROM table_name GROUP BY col1, col2, ... HAVING (COUNT(col1) > 1) AND (COUNT(col2) > 1) AND ... In the above query, we do a GROUP BY of all the columns (col1, col2) for whom we want to find duplicates.


2 Answers

You re looking for the LIKE operator

Pattern matching using SQL simple regular expression comparison. Returns 1 (TRUE) or 0 (FALSE). If either expr or pat is NULL, the result is NULL.

Something like

SELECT  keyword 
FROM    table 
WHERE   ('Tell me about admission info' LIKE CONCAT('%', keyword, '%'))

SQL Fiddle DEMO

like image 186
Adriaan Stander Avatar answered Oct 16 '22 20:10

Adriaan Stander


This work fine, using REGEXP:

SELECT  keyword 
FROM    table 
WHERE   'Tell me about admission info' REGEXP keyword;

But this work only if keyword don't contain Regular expression's escapes...

I.e. This will work fine while keyword contain only letters, numbers, spaces and so on.

like image 40
F. Hauri Avatar answered Oct 16 '22 21:10

F. Hauri