简体   繁体   中英

Which mysql select is better/faster?

Is there a preferred way? There are currently 1640 rows in the game table to go through and will be adding about 1200 every year.

SELECT `date` FROM `game` WHERE `date`<'2009-11-09' ORDER BY `date` DESC LIMIT 1;

0.0004 seconds

SELECT MAX(`date`) AS `date` FROM `game` WHERE `date`<'2009-11-09' LIMIT 1;

0.0006 seconds

The speeds were for the first time this ran. Each time after was 0.0002 for each.

mySQL:
Server: Localhost via UNIX socket
Server version: 5.1.37

PHP (shouldn't be relevant):
5.x

Apply MySQL EXPLAIN and check the query plans. The second example may well have a cleaner plan, which is nice as it looks cleaner to my eye. (Once you remove the limit.)

A noddy test locally shows (no indexes).

Query 1:

EXPLAIN
SELECT  datex
FROM    TABLE_X x
WHERE   datex < "2009-10-20"
ORDER BY datex DESC
LIMIT 1

Plan

id select_type table type possible_keys key  key_len ref  rows Extra
1  SIMPLE      x     ALL  NULL          NULL NULL    NULL 2    Using where; Using filesort

Query 2:

EXPLAIN
SELECT  MAX( datex )
FROM    TABLE_X x
WHERE   datex < "2009-10-20"

Plan

id  select_type table type  possible_keys   key     key_len ref   rows Extra
1   SIMPLE      x     ALL   NULL            NULL    NULL    NULL  2    Using where

With those numbers of rows and the simplicity of the queries, it should not matter. You also do not need the limit on the second query. Just choose whichever one is easier for you to understand.

In second query you don't have to add LIMIT 1 . It will always return 1 row. I would say that second query is more readable and you should use. But I agree with @jle. You have very small database and it really does not affect performance very much.

You can look at what the plan is (ie how mysql does the work) using explain - http://dev.mysql.com/doc/refman/5.0/en/explain.html

I imagine they are pretty much identical, but that's the best way to check (it may depend on indices etc).

But I have to ask - do you really need to worry about this? It's not exactly slow, and the table isn't growing at a huge rate.

Finally, you don't need the second "limit".

I would also want to add to all the other responses:

try to add a million records. Best way to know for sure.

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