PHP/SQL: ORDER BY or sort($array)?

后端 未结 6 1077
你的背包
你的背包 2020-12-19 05:36

Which do you think is faster in a PHP script:

$query = \"SELECT... FROM ... ORDER BY first_val\";

or

while($row = odbc_fet         


        
6条回答
  •  误落风尘
    2020-12-19 06:05

    If there's a LIMIT on the first query, and the set of rows the query would match without the LIMIT is much larger than the LIMIT, then ORDER BY on the query is DEFINITELY faster.

    That is to say, if you need the top 50 rows from a 10,000 row table, it's much faster to have the database sort for you, and return only those top 50 rows, than it is to retrieve all 10,000 rows and sort them yourself in PHP. This is probably representative of the vast majority of what will happen in real-world applications

    If there are any cases at all in which sorting in PHP is even comparable, they're few and far between.

    Additionally, SQL sorting is much more powerful -- it's trivial to sort on multiple columns, subqueries, the return values of aggregate functions etc.

提交回复
热议问题