mysql中字串索引問題與例子

來源:互聯網
上載者:User

事情的起因是線上日誌發現的mysql慢查詢。100萬資料量的標準,聯集查詢全部走索引的情況下,盡然要600多毫秒。很不解,但是將索引列由varchar(50)型改為bigint型後,資料提升了30倍。究其原因就索引樹上搜尋時要進行大量的比較操作,而字串的比較比整數的比較耗時的多。

所以建議一般情況下不要在字串列建立索引,如果非要使用字串索引,可以採用以下兩種方法:

1.只是用字串的最左邊n個字元建立索引,推薦n<=10;比如index left(address,8),但是需要知道首碼索引不能在order by中使用,也不能用在索引覆蓋上。

2.對字串使用hash方法將字串轉化為整數,address_key=hashToInt(address),對address_key建立索引,查詢時可以用如下查詢where address_key = hashToInt(‘beijing,china’) and address = ‘beijing,china’;

例子

我在下列語句中發現了一個問題:

select * from region where city like "任丘%" limit 10;
select * from region where city like "商丘%" limit 10;

這兩個語句的結果是一樣的,

類似的情況如下:

select * from region where city like "臨安市%" limit 10;
select * from region where city like "六安市%" limit 10;

臨海市 龍海市
棗陽市 益陽市
溫州市 梧州市

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.