我的SQL查询有改进吗?

时间:2011-04-19 20:08:56

标签: php mysql

有没有办法用其他东西删除MAX,可能是ASC LIMIT 1来减少数据库限制?我的查询获取最大ID并将其加1。

这是我的疑问:

$query = 'SELECT MAX(ID) +1 as maxidpost  
          FROM wp_posts';
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
  echo 'p='. $row['maxidpost'];
}
mysql_close();

4 个答案:

答案 0 :(得分:0)

数据库告诉您有关查询的内容?如果id被索引,那么

mysql> explain select max(id) + 1 from times;
+----+-------------+-------+------+---------------+------+---------+------+------+------------------------------+
| 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.18 sec)

mysql> explain select id from times order by id ASC limit 1;
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | times | index | NULL          | PRIMARY | 4       | NULL |    1 | Using index |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
1 row in set (0.00 sec)

答案 1 :(得分:0)

这很好。添加limit 1并不会带来明显的性能提升。

这不应该导致任何类型的问题,您是否遇到此特定查询的问题?

答案 2 :(得分:0)

SQL MAX()函数将自动查找一个结果。任何方式都不需要LIMIT它。如果您想改进该查询,请尝试将ID设置为索引。

答案 3 :(得分:0)

SELECT ID + as maxidpost FROM wp_posts ORDER BY ID DESC LIMIT 1; 或者如果表具有Auto_increment ID SHOW TABLE STATUS LIKE 'wp_posts'; 应该有一个名为Auto_increment的字段,它应该是MAX(ID)+ 1;