MySQL LIKE query using column contents
Jan 14, 2008
I recently needed to build a query that would filter results by comparing a value from one table against another. This is relatively simple if you're checking for equality, but if you need to use MySQL's LIKE to compare strings, then things get hairy. My attempt at:SELECT
shows.*
FROM
shows, states
WHERE
states.id = shows.state_id AND
shows.location LIKE %states.abbreviation Failed miserably. After some thought I realized that, because MySQL is looking for a string constant when using LIKE, I needed a way for the value of the column in question to be considered a constant but also prepend the wildcard '%' character in front of it. Here's the solution I came up with, and it works beautifully: SELECT
shows.*
FROM
shows, states
WHERE
states.id = shows.state_id AND
shows.location LIKE concat('%', states.abbreviation) Without a string concatenation character built into the syntax of MySQL, the use of the concat() function is required. It takes an arbitrary number of parameters that will evaluate into a single string constant. I couldn't find much from Google on this particular use of LIKE, so I hope someone finds this post useful.
4 commentsnewbie
Apr 14, 2008
Thanks! Spent all long time debugging this until I came across your post.
Chris
May 22, 2008
Wow, this is extremely useful :-) Thanks for the post!
Duo
May 27, 2008
Nice post! Save me lots of time.
But since the function is used at right-hand side, perhaps it would be slow for very large table.






xentek