Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL like another field

Tags:

mysql

sql-like

I have a table with two string columns: Url and ModelId. I need to return records for which Url contains ModelId, something like this:

SELECT Id, Url, ModelId WHERE Url like "%ModelId%" 
like image 420
SiberianGuy Avatar asked Feb 03 '11 12:02

SiberianGuy


People also ask

How do I use like between two columns in SQL?

The SQL LIKE OperatorThe 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 MySQL have Ilike?

In MySQL you do not have ILIKE. Checkout MySQL docs on string comparison functions.

How can I check if one column value is present in another column in SQL?

The SQL EXISTS Operator The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.


2 Answers

SELECT Id, Url, ModelId  WHERE Url LIKE CONCAT('%', ModelId, '%') 
like image 169
Michael Robinson Avatar answered Sep 21 '22 06:09

Michael Robinson


You can not just concat the strings, you must also escape the field from % and _:

SELECT Id, Url, ModelId  WHERE Url LIKE CONCAT('%', REPLACE(REPLACE(ModelId,'%','\%'),'_','\_'), '%'), '%') 
like image 31
tal952 Avatar answered Sep 21 '22 06:09

tal952