MySQL解釋查詢的奇怪邏輯

來源:互聯網
上載者:User

我用的是MySQL 4.1.20 。一直以為,當表的某列出現在查詢語句的order by中時,如果這個列建了索引,MySQL利用這個索引。現在才發現這個想當然是錯誤的。

這幾天對資料庫的跟蹤我發現總是有一些特簡單的SQL執行起來特別慢。

如:select id,title from sources  where status=1 and isrepeat=0 order by id desc limit 0,30;
這個查詢執行大概需要3s。表sources大概有26萬資料,id是自增主鍵,status和isrepeat都建了索引。使用explain看一下MySQL是怎麼解釋他的:

sources ref status_2 status_2 3 const,const 178760 Using where; Using filesort

居然沒有用到主鍵索引(id)。再看看MySQL是怎麼解釋幾乎同樣的SQL(select id,title from sources  where status=1 and isrepeat=0 and id>0 order by id desc limit 0,30;):

sources range PRIMARY,status_2 PRIMARY 4 NULL 52704 Using where

執行這條查詢只需0.00011s。只是加入了and id>0,差別竟然這麼大。

也許是我使用的Mysql版本沒有跟上時代吧,有空拿最新的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.