35

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,621
  • 3
  • 20
  • 33
SiberianGuy
  • 23,286
  • 52
  • 142
  • 260
  • 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

101
SELECT Id, Url, ModelId 
WHERE Url LIKE CONCAT('%', ModelId, '%')
Michael Robinson
  • 28,575
  • 12
  • 103
  • 128
  • 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
4

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
  • 845
  • 10
  • 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
  • 3,937
  • 11
  • 45
  • 77
-1
SELECT Id, Url, ModelId from <table> WHERE Url like '%' + ModelId + '%'
Sachin Shanbhag
  • 52,879
  • 11
  • 86
  • 103