MySQL short circuit OR

table  
id | word

SELECT id FROM table WHERE 
word = "hello" OR 
word = "ello" OR 
word = "llo" OR 
word = "lo" OR 
word = "o"

I need to get only the first identifier that is found. If not the first, then the second. If not the second, then the third ....
Is it possible to get only the first OR that is in the database without checking all of them?

+3
source share
5 answers
ORDER BY length(word) DESC LIMIT 1
+1
source

You cannot do it this way, but the easiest way to process your request would be

ORDER BY length(word) DESC

This will first return the longest (best matches) results, so you can use LIMITon it.

+1
source

LIMIT 1

0

.

mysql> select * from words;
+----+-------+
| id | word  |
+----+-------+
|  1 | hello | 
|  2 | ello  | 
|  3 | llo   | 
|  4 | lo    | 
|  5 | o     | 
+----+-------+
5 rows in set (0.00 sec)


SELECT id
FROM   (SELECT id
        FROM   words
        WHERE  word = 'hello'
        UNION
        SELECT id
        FROM   words
        WHERE  word = 'ello'
        UNION
        SELECT id
        FROM   words
        WHERE  word = 'llo'
        UNION
        SELECT id
        FROM   words
        WHERE  word = 'lo'
        UNION
        SELECT id
        FROM   words
        WHERE  word = 'o') w
LIMIT  1; 
0

, , .

, REGEXP.

This will match any word ending with o
SELECT name FROM pet WHERE name REGEXP 'o $' ORDER BY length (name) DESC LIMIT 1;

http://dev.mysql.com/doc/refman/5.0/en/regexp.html#operator_regexp

0
source

Source: https://habr.com/ru/post/1735921/


All Articles