MySQL like another field

2020-02-23 07:03发布

问题:

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%"

回答1:

SELECT Id, Url, ModelId 
WHERE Url LIKE CONCAT('%', ModelId, '%')


回答2:

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,'%','\%'),'_','\_'), '%'), '%')


回答3:

Here is the query:

SELECT Id, Url, ModelId WHERE Url LIKE CONCAT('%', ModelId, '%')


回答4:

SELECT Id, Url, ModelId from <table> WHERE Url like '%' + ModelId + '%'