Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse LIKE %...% possible?

Tags:

mysql

In short I want to match a dictionary entry to a row of text, but it doesn't have to match the whole row, just the beginning. So it's in effect a sort of reverse LIKE %...%

For example,

SELECT * FROM `dictionary` WHERE
    (`simplified` = '铅笔的历史非常悠久,它起源于2000多年'
    OR `simplified` = '铅笔的历史非常悠久,它起源于2000多'
    OR `simplified` = '铅笔的历史非常悠久,它起源于2000'
    OR `simplified` = '铅笔的历史非常悠久,它起源于200'
    OR `simplified` = '铅笔的历史非常悠久,它起源于20'
    OR `simplified` = '铅笔的历史非常悠久,它起源于2'
    OR `simplified` = '铅笔的历史非常悠久,它起源于'
    OR `simplified` = '铅笔的历史非常悠久,它起源'
    OR `simplified` = '铅笔的历史非常悠久,它起'
    OR `simplified` = '铅笔的历史非常悠久,它'
    OR `simplified` = '铅笔的历史非常悠久,'
    OR `simplified` = '铅笔的历史非常悠久'
    OR `simplified` = '铅笔的历史非常悠'
    OR `simplified` = '铅笔的历史非常'
    OR `simplified` = '铅笔的历史非'
    OR `simplified` = '铅笔的历史'
    OR `simplified` = '铅笔的历'
    OR `simplified` = '铅笔的'
    OR `simplified` = '铅笔'
    OR `simplified` = '铅')
    ORDER BY CHAR_LENGTH(`simplified`) DESC;

This works and does what I need but I know it's grossly inefficient. Is there any other way of doing it? Help much appreciated!!

Example results:

97576   铅笔
97484   铅
97566   铅
like image 925
raininglemons Avatar asked Mar 20 '23 04:03

raininglemons


1 Answers

how about

WHERE `simplified` = SUBSTRING(
  '铅笔的历史非常悠久,它起源于2000多年',
  0, CHAR_LENGTH(`simplified`))

? Probably not indexable, but at least the query is short. :)

And you can probably optimize it by adding

AND `simplified` LIKE '铅%'

to reject all the rows that don't at least start with the right character.

like image 81
hobbs Avatar answered Mar 29 '23 08:03

hobbs