Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use LIKE %..% with field values in MySQL

I stumbled into a delicate SQL problem when I needed to use a value from a field inside a LIKE %..% statement.

Example:

SELECT t1.Notes, t2.Name FROM Table1 t1, Table2 t2 WHERE t1.Notes LIKE '%t2.Name%' 

This is only an example from the top of my head to show what I need to do (I know this will not work). I need to use the value of t2.Name inside the LIKE %..%

I guess this is trivial when you know it ;)

like image 510
Max Kielland Avatar asked Dec 12 '10 05:12

Max Kielland


People also ask

Can we use like operator on columns?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Does like work in MySQL?

It is in PostgreSQL the keyword ILIKE can be used instead of LIKE to make the match case-insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension. In MySQL you do not have ILIKE.

How use like and not like in MySQL?

MySQL NOT LIKE is used to exclude those rows which are matching the criterion followed by 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.


1 Answers

Use:

SELECT t1.Notes,         t2.Name   FROM Table1 t1   JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%') 
like image 101
OMG Ponies Avatar answered Sep 18 '22 10:09

OMG Ponies