简体   繁体   中英

How to find the longest matching string from a input string

A table, named strings, contains various strings, and unique id's:

在此处输入图片说明

Question is, how to write a query that takes an input string, and return the id of the longest matching (sub) string in the strings table?

The matching string, may, or may not be a substring of the input string. Comparison starts at string index 0.

Inputs and expected output:

INPUT -> OUTPUT
ABC    -> 1
ABCD   -> 2
ABCKK  -> 1
ABCDDD -> 2
CDA    -> NULL
CABC   -> NULL

Doing this:

SET @theString = 'ABCBBB';
SELECT id FROM strings WHERE a_string LIKE @theString;

only returns the correct result when the input string exactly matches a string in the table, and don't work when the 'a_string' is a substring.

You can use:

select s.*
from strings s
where @theString regexp a_string
order by length(a_string) desc
limit 1;

In regards of using LIKE , you need to set the wildcards for it to work as the filter you want. If you are not required to set a variable, you can use the following query.

SELECT id FROM strings
WHERE a_string LIKE '%ABC%'
ORDER BY length(a_string) DESC LIMIT 1;

or if you need a variable, it can be done with the CONCAT function

SELECT id FROM strings
WHERE a_string LIKE CONCAT('%',@theString,'%')
ORDER BY length(a_string) DESC LIMIT 1;

This just is an alternative to @Gordon Linoff's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM