mysql語句執行順序

來源:互聯網
上載者:User

標籤:

  今天工作中遇到多個表關聯查詢需求,其實這種需求也不是今天才遇到,之前多多少少都有遇到過,個人非常不喜歡用關聯查詢,覺得會拖慢資料庫,而且對關聯查詢的語句執行順序有很多的不明白,但是今天這個需求要使用四個表關聯查詢,如果一個一個的查,覺得太麻煩,而且現在使用yii2.0的架構,通過hasone和joinwith函數可以很方便的關聯查詢,不用自己再去寫sql查詢語句。問題是解決了,但是對多個表的關聯查詢順序的疑問卻是一點也沒有降低,於是就花點時間研究了下,發現一篇不錯的文章。轉載如下:

MySQL的語句一共分為11步,如所標註的那樣,最先執行的總是FROM操作,最後執行的是LIMIT操作。其中每一個操作都會產生一張虛擬表,這個虛擬表作為一個處理的輸入,只是這些虛擬表對使用者來說是透明的,但是只有最後一個虛擬表才會被作為結果返回。如果沒有在語句中指定某一個子句,那麼將會跳過相應的步驟。

下面我們來具體分析一下查詢處理的每一個階段
  1. FORM: 對FROM的左邊的表和右邊的表計算笛卡爾積。產生虛表VT1
  2. ON: 對虛表VT1進行ON篩選,只有那些符合<join-condition>的行才會被記錄在虛表VT2中。
  3. JOIN: 如果指定了OUTER JOIN(比如left join、 right join),那麼保留表中未匹配的行就會作為外部行添加到虛擬表VT2中,產生虛擬表VT3, rug from子句中包含兩個以上的表的話,那麼就會對上一個join串連產生的結果VT3和下一個表重複執行步驟1~3這三個步驟,一直到處理完所有的表為止。
  4. WHERE: 對虛擬表VT3進行WHERE條件過濾。只有符合<where-condition>的記錄才會被插入到虛擬表VT4中。
  5. GROUP BY: 根據group by子句中的列,對VT4中的記錄進行分組操作,產生VT5.
  6. CUBE | ROLLUP: 對錶VT5進行cube或者rollup操作,產生表VT6.
  7. HAVING: 對虛擬表VT6應用having過濾,只有符合<having-condition>的記錄才會被 插入到虛擬表VT7中。
  8. SELECT: 執行select操作,選擇指定的列,插入到虛擬表VT8中。
  9. DISTINCT: 對VT8中的記錄進行去重。產生虛擬表VT9.
  10. ORDER BY: 將虛擬表VT9中的記錄按照<order_by_list>進行排序操作,產生虛擬表VT10.
  11. LIMIT:取出指定行的記錄,產生虛擬表VT11, 並將結果返回。

 

再引用一段書上的解釋

 

The actual execution of SQL statements is a bit tricky. However, the standard does specify the order of interpretation of elements in the query. This is basically in the order that you specify, although I think having and group by could come after select:

FROM clause
WHERE clause
SELECT clause
GROUP BY clause
HAVING clause
ORDER BY clause
This is important for understanding how queries are parsed. You cannot use a column alias defined in a select in the where clause, for instance, because the where is parsed before the select. On the other hand, such an alias can be in the order by clause.

As for actual execution, that is really left up to the optimizer. For instance:

. . .
group by a, b, c
order by NULL
and

. . .
group by a, b, c
order by a, b, c
both have the effect of the "order by" not being executed at all -- and so not executed after the group by (in the first case, the effect is to remove sorting from the group by and in the second the effect is to do nothing more than the group by already does).

mysql語句執行順序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.