PHP - SQL优化min / max太慢

时间:2017-09-04 08:28:17

标签: php mysql performance optimization

我在查询时遇到一些问题,这些查询会找到包含特定过滤器的订单的下一个ID - 就像它应该来自特定城市等等。

目前它用于一个功能,它会根据当前的顺序吐出上一个或下一个ID。所以它可以是min(id)或max(id),其中max(id)显然更快,因为它必须通过更少的行。

查询工作正常,但速度相当慢,因为它通过123953行查找ID。有什么办法可以优化吗?

功能示例:

SELECT $minmax(orders.orders_id) AS new_id FROM orders LEFT JOIN orders_status ON orders.orders_status = orders_status.orders_status_id $where_join WHERE orders_status.language_id = '$languages_id' AND orders.orders_date_finished != '1900-01-01 00:00:00' AND orders.orders_id $largersmaller $ordersid $where;

实例

SELECT min(orders.orders_id)
FROM orders 
LEFT JOIN orders_status ON orders.orders_status = orders_status.orders_status_id
WHERE orders_status.language_id = '4' 
  AND orders.orders_date_finished != '1900-01-01 00:00:00' 
  AND orders.orders_id < 4868771 
LIMIT 1

1 个答案:

答案 0 :(得分:0)

如此总结:

SELECT orders.orders_id
FROM orders 
JOIN orders_status ON orders.orders_status = orders_status.orders_status_id
WHERE orders_status.language_id = '4' 
  AND orders.orders_date_finished != '1900-01-01 00:00:00' 
  AND orders.orders_id < 4868771 
ORDER BY orders.orders_id ASC
LIMIT 1

额外:

要获取MAX值,请在ASC现在使用DESC。

看看你的问题:一定要逃避$ language_id etcetera等值。我想他们可能来自某些HTML形式? (或使用准备好的陈述)