Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql match string with start of string in table

Tags:

I realise that it would be a lot easier if I could modify the table when it was created, but assuming I can't, I have a table that is such as:

abcd abde abdf abff bbsdf bcggs ... snip large amount zza 

The values in the table are not fixed length. I have a string to match such as abffagpokejfkjs . If it was the other way round, I could do

SELECT * from table where value like 'abff%' 

but I need to select the value that matches the start of a string that is provided.

Is there a quick way of doing that, or does it need an itteration through the table to find a match?

like image 432
Woody Avatar asked Mar 12 '12 12:03

Woody


Video Answer


1 Answers

Try this:

SELECT col1, col2 -- etc... FROM your_table WHERE 'abffagpokejfkjs' LIKE CONCAT(value, '%') 

Note that this will not use an index effectively so it will be slow if you have a lot of records.

Also note that some characters in value (e.g. %) may be interpreted by LIKE as having a special meaning, which may undesirable.

like image 88
Mark Byers Avatar answered Sep 18 '22 13:09

Mark Byers