Say I have this:
page_url | canvas_url
---------------------------------------------------------------
http://www.google.com/ | http://www.google.com/barfoobaz
http://www.google.com/foo/bar | http://www.google.com/foo
I’d like to find the row that is the start of my string ordered by the longest match. The problem I’m facing is finding the longest matching string, rather than just the row that matches that also has a matching one. I.e.
http://www.google.com/foo matches page_url in row 1 and canvas_url in row 2, but if it’s length of both columns rather than a match it would think row 1 is the better match as canvas_url in row 1 is longer.
I could grab all matches and then filter the length in code doing something like:
SELECT *, LENGTH(canvas_url), LENGTH(page_url)
FROM app
WHERE
'http://www.google.com/foo' LIKE CONCAT(canvas_url, '%') OR
'http://www.google.com/foo' LIKE CONCAT(page_url, '%')
Or perform 2 subselections grabbing the top matches of canvas_url respective page_url and then filter that to 1 in code, but I would prefer (barring any ridiculous performance issues) having the database just return what I need.
My immediate concern is MySQL but I need to target SQLite and Postgress, so I’d be happy with an answer in either of those.
Suggestions?
This will work to get the longest actual match length (not just the longest url in the record):
Here is a running example on SqlFiddle.