gpt4 book ai didi

MySQL/MariaDB - 按内部子查询排序

转载 作者:IT老高 更新时间:2023-10-29 00:20:13 24 4
gpt4 key购买 nike

多年来,我在 MySQL 5.5(或以前的版本)中使用了以下查询,没有任何问题:

SELECT t2.Code from (select Country.Code from Country order by Country.Code desc ) AS t2;

结果的顺序总是按我的需要降序。

上周,我刚刚迁移到一个新的 MySQL 版本(实际上,我迁移到了 MariaDB 10.0.14),现在使用相同数据库的相同查询不再按降序排序。是升序排序的(或者是自然排序,其实不确定)。

那么,谁能告诉我这是一个错误,还是最近版本的 MySQL/MariaDB 的行为发生了变化?

最佳答案

经过一些挖掘,我可以确认您的两种情况:

MySQL 5.1 确实在子查询中应用了 ORDER BY

当未提供 LIMIT 时,Linux 上的 MariaDB 5.5.39 不会在子查询中应用 ORDER BY。它确实但是在给出相应的 LIMIT 时正确应用订单:

SELECT t2.Code 
FROM (
SELECT Country.Code FROM Country ORDER BY Country.Code DESC LIMIT 2
) AS t2;

如果没有 LIMIT,就没有充分的理由在子查询中应用排序。它可以等效地应用于外部查询。

记录的行为:

事实证明,MariaDB has documented this behavior并且它不被视为错误:

A "table" (and subquery in the FROM clause too) is - according to the SQL standard - an unordered set of rows. Rows in a table (or in a subquery in the FROM clause) do not come in any specific order. That's why the optimizer can ignore the ORDER BY clause that you have specified. In fact, SQL standard does not even allow the ORDER BY clause to appear in this subquery (we allow it, because ORDER BY ... LIMIT ... changes the result, the set of rows, not only their order).

You need to treat the subquery in the FROM clause, as a set of rows in some unspecified and undefined order, and put the ORDER BY on the top-level SELECT.

因此 MariaDB 还建议在最外层查询中应用 ORDER BY,或在必要时应用 LIMIT

注意:我目前无法访问适当的 MySQL 5.5 或 5.6 来确认那里的行为是否相同(并且 SQLFiddle.com 出现故障)。 Comments on the original bug report (作为非错误关闭)表明 MySQL 5.6 的行为方式可能与 MariaDB 相同。

关于MySQL/MariaDB - 按内部子查询排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26372511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com