获得列的最大值

时间:2010-01-02 17:40:45

标签: mysql database

这些陈述之间是否有任何明显的差异(速度/效率)?假设该列已编入索引。

SELECT MAX(someIntColumn) AS someIntColumn

SELECT someIntColumn ORDER BY someIntColumn DESC LIMIT 1

2 个答案:

答案 0 :(得分:6)

这在很大程度上取决于SQL实现中的查询优化器。充其量,他们将具有相同的表现。但是,通常情况下,第一个查询可能要快得多。

第一个查询实质上要求DBMS检查someIntColumn中的每个值并选择最大值。

第二个查询要求DBMS将someIntColumn中的所有值从最大值排序到最小值并选择第一个值。根据表中的行数以及列上索引的存在(或缺少),这可能会明显变慢。

如果查询优化器足够复杂,可以意识到第二个查询等同于第一个查询,那么你很幸运。但是,如果您将应用程序重新定位到另一个DBMS,则可能会出现意外的糟糕性能。

答案 1 :(得分:0)

根据解释计划进行编辑:

解释计划表明max(column)更有效率。解释计划说,“Select tables optimized away”

EXPLAIN SELECT version from schema_migrations order by version desc limit 1;
+----+-------------+-------------------+-------+---------------+--------------------------+---------+------+------+-------------+
| id | select_type | table             | type  | possible_keys | key                      | key_len | ref  | rows | Extra       |
+----+-------------+-------------------+-------+---------------+--------------------------+---------+------+------+-------------+
|  1 | SIMPLE      | schema_migrations | index | NULL          | unique_schema_migrations | 767     | NULL |    1 | Using index | 
+----+-------------+-------------------+-------+---------------+--------------------------+---------+------+------+-------------+
1 row in set (0.00 sec)

EXPLAIN SELECT max(version) FROM schema_migrations ;
+----+-------------+-------+------+---------------+------+---------+------+------+------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra                        |
+----+-------------+-------+------+---------------+------+---------+------+------+------------------------------+
|  1 | SIMPLE      | NULL  | NULL | NULL          | NULL | NULL    | NULL | NULL | Select tables optimized away | 
+----+-------------+-------+------+---------------+------+---------+------+------+------------------------------+
1 row in set (0.00 sec)
相关问题