38

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%"
r.vengadesh
  • 1,721
  • 3
  • 20
  • 36
SiberianGuy
  • 24,674
  • 56
  • 152
  • 266
  • 1
    possible duplicate of [Use LIKE %..% with field values in MySQL](http://stackoverflow.com/questions/4420554/use-like-with-field-values-in-mysql) – Richard Ayotte Nov 22 '13 at 21:22

4 Answers4

108
SELECT Id, Url, ModelId 
WHERE Url LIKE CONCAT('%', ModelId, '%')
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
  • 5
    Technically you might want to escape the field in case it has % in it: LIKE CONCAT('%',REPLACE(field,'%','\%'),'%') – dlo May 21 '15 at 21:58
5

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,'%','\%'),'_','\_'), '%'), '%')
tal952
  • 953
  • 12
  • 18
  • 1
    Great point. Question: should you also escape the '\' character? `REPLACE(REPLACE(REPLACE(ModelId,'\\','\\\\'),'%','\%'),'_','\_')` – drwatsoncode Aug 24 '20 at 20:32
3

Here is the query:

SELECT Id, Url, ModelId WHERE Url LIKE CONCAT('%', ModelId, '%')
Erba Aitbayev
  • 4,167
  • 12
  • 46
  • 81
-1
SELECT Id, Url, ModelId from <table> WHERE Url like '%' + ModelId + '%'
Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103