Stop MySQL after the first match

I noticed that adding LIMIT 1at the end of the request does not reduce the execution time. I have several thousand records and a simple query. How to make MySQL stop after the first match?

For example, these two queries take about half a second:

SELECT id,content FROM links WHERE LENGTH(content)<500 ORDER BY likes

SELECT id,content FROM links WHERE LENGTH(content)<500 ORDER BY likes LIMIT 1

Edit: And here are the results of the explanation:

id | select_type | table | type possible_keys | key | key_len | ref | rows | Extra
1 | SIMPLE | links | ALL | NULL | NULL | NULL | NULL | 38556 | Using where; Using filesort
+4
source share
2 answers

The difference between the execution time of two requests depends on the actual data.

There are several possible scenarios:

There are many records with LENGTH(content)<500

MySQL ( , ORDER BY). , WHERE . LENGTH(content)<500, LIMIT , .

LENGTH(content)<500 , MySQL , , , . , . .

, , , , .

Edit , ORDER BY, :

  • , ORDER BY , , , , WHERE ( 66% , , LIMIT).

  • , ORDER BY - MySQL , , WHERE, , . ( , 1 ...)!

+1

, . , , , , :

ALTER TABLE links ADD COLUMN content_length INT
UPDATE links SET content_length=LENGTH(content)
ALTER TABLE links ADD INDEX idx_content_length (content_length)

, , . , content_length , .

0

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


All Articles