MySQL 子查詢中order by不生效問題 問題描述 排查過程 問題根因 總結 參考文檔

一個偶然的機會,發現一條SQL語句在不同的MySQL實例上執行得到了不同的結果。

問題描述

創建商品表product_tbl和商品操作記錄表product_operation_tbl兩個表,來模擬下業務場景,結構和數據如下:

接下來需要查詢所有商品最新的修改時間,使用如下語句:

select t1.id, t1.name, t2.product_id, t2.created_at  from product_tbl t1 left join (select * from product_operation_log_tbl order by created_at desc) t2 on t1.id = t2.product_id group by t1.id;

通過結果可以看到,子查詢先將product_operation_log_tbl裏的所有記錄按創建時間(created_at)逆序,然後和product_tbl進行join操作,進而查詢出的商品的最新修改時間。

在區域A的MySQL實例上,查詢商品最新修改時間可以得到正確結果,但是在區域B的MySQL實例上,得到的修改時間並不是最新的,而是最老的。通過對語句進行簡化,發現是子查詢中的order by created_at desc語句在區域B的實例上沒有生效。

排查過程

難道區域會影響MySQL的行爲?經過DBA排查,區域A的MySQL是5.6版,區域B的MySQL是5.7版,並且找到了這篇文章:

mysql 5.7 5.6排序mysql 5.6升級到5.7之後 子查詢裏面的order排序無效火鍋與理想的博客-CSDN博客

根據文章的描述,MySQL 5.7版會忽略掉子查詢中的order by語句,可令人疑惑的是,我們模擬業務場景的MySQL是8.0版,並沒有出現這個問題。使用docker分別啓動MySQL 5.6、5.7、8.0三個實例,來重複上面的操作,結果如下:

可以看到,只有MySQL 5.7版忽略了子查詢中的order by。有沒有可能是5.7引入了bug,後續版本又修復了呢?

問題根因

繼續搜索文檔和資料,發現官方論壇中有這樣一段描述:

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.

問題的原因清晰了,原來SQL標準中,table的定義是一個未排序的數據集合,而一個SQL子查詢是一個臨時的table,根據這個定義,子查詢中的order by會被忽略。同時,官方回覆也給出瞭解決方案:將子查詢的order by移動到最外層的select語句中。

總結

  • 在SQL標準中,子查詢中的order by是不生效的
  • MySQL 5.7由於在這個點上遵循了SQL標準導致問題暴露,而在MySQL 5.6/8.0中這種寫法依然是生效的

參考文檔

https://stackoverflow.com/questions/26372511/mysql-mariadb-order-by-inside-subquery

https://mariadb.com/kb/en/why-is-order-by-in-a-from-subquery-ignored/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章