mysql: how to save ORDER BY after LEFT JOIN without reorder?

前端 未结 4 866
你的背包
你的背包 2021-01-22 22:22

I\'ve two table:

1) profiles

+----+---------+
| id | name    |
+----+---------+
|  1 | WILLIAM |
|  2 | JOHN    |
|  3 | ROBERT  |
|  4 | MI         


        
4条回答
  •  时光取名叫无心
    2021-01-22 22:58

    (Explaining the loss of ORDER BY)

    The SQL standard essentially says that a subquery is an unordered set of rows. This implies that the Optimizer is free to ignore the ORDER BY in the 'derived' table: FROM ( SELECT ... ORDER BY ). In "recent" versions of MySQL and MariaDB, such ORDER BYs are being dropped. There are other cases where ORDER BY is ignored.

    In some situations (not sure about this one), adding a LIMIT 99999999 (big number) after the ORDER BY tricks the Optimizer into doing the ORDER BY. However, it is still free to ignore the "order" later.

    A general rule for MySQL: Avoid subqueries. (There are cases where subqueries are faster, but not yours.)

    A strong rule: You must have an ORDER BY on the outermost if you want the results to be sorted.

    If you had added LIMIT 3 to the derived table in your first query, you would get only CHARLES, DAVID, JAMES, but not necessarily in that order. That is, you would need two ORDER BYs - one in the derived table, one at the very end.

提交回复
热议问题