MySQL索引用法例項分析

2022-09-26 00:21:09 字數 2492 閱讀 9877

mysql描述:

乙個文章庫,裡面有兩個表:category和art程式設計客棧icle。category裡面有10條分類資料。article裡面有20萬條。article裡面有乙個"article_category"欄位是與category裡的"category_id"字段相對應的。article表裡面已經把 article_category字義為了索引。資料庫大小為1.3g。

問題描述:

執行乙個很普通的查詢:

複製** **如下:

select from `article` where article_category=11 order by article_id desc limit 5

執行時間大約要5秒左右

解決方案:

建乙個索引:

複製** **如下:

create index 程式設計客棧idx_u on article (article_category,article_id);

複製** **如下:

select * from `article` where article_category=11 order by article_id desc limit 5

減少到0.0027秒

繼續問題:

複製** **如下:

select * from `article` where article_category in (2,3) order by article_id desc limit 5

執行時間要11.2850秒。

使用or:

select * from article

where article_category=2

or article_category=3

order by article_id desc

limit 5

執行時間:11.0777

解決方案:避免使用in 或者 or (or會導致掃表),使用union all

使用union all:

(select * from articlebbntafpe where article_category=2 order by article_id desc limit 5)

union all (select * from article where article_category=3 order by article_id desc limit 5)

order by article_id desc

limit 5

執行時間:0.0261

注:union 和union all 的區別

在資料庫中,union和union all關鍵字都是將兩個結果集合並為乙個,但這兩者從使用和效率上來說都有所不同。

union在進行表鏈結後會篩選掉重複的記錄,所以在表鏈結後會對所產生的結果集進行排序運算,刪除重複的記錄再返回結果。

實際大部分應用中是不會產生重複的記錄,最常見的是過程表與歷史表union。如:

select * from gc_dfys union select * from ls_jg_dfys

這個sql在執行時先取出兩個表的結果,再用排序空間進行排序刪除重複的記錄,最後返回結果集,如果表資料量大的話可能會導致用磁碟進行排序。

而union all只是簡單的將兩個結果合併後就返回。這樣,如果返回的兩個結果集中有重複的資料,那麼返回的結果集就會包含重複的資料了。

從效率上說,union all 要比union快很多,所以,如果可以確認合併的兩個結果集中不包含重複的資料的話,那麼就使用union all,如下:

select * from gc_dfys union all select * from ls_jg_dfys

注:mysql中union all的order by問題

今天寫mysql資料庫**的時候,發現union的結果不是預期的

$stime = date("h:i:s");

$sql1 = "select * from t where '$stime'>stime order by stime desc";

$sql2 = "select * from t where stime>'$stimwww.cppcns.come' order by stime asc";

$sql = "($sql) union all ($sql2)";

分別執行$sql1 和 $sql2 的時候結果是對的

但是執行$sql的時候,發現結果反了,$sql1的部分變公升序,$sql2的部分變成降序

搜尋也沒有得到滿意的答案,好像有些資料庫還是不支援字句order by 的

無意中發現這樣可以:

複製** **如下:

$sql = "select * from ($sql1) as temp1 union all select * from ($sql2) as temp2";

這是因為你的union的用法不正確的原因。在union操作中,order by語句不能出現在由union操作組合的兩個select語句中。排序可以通過在第二個select語句後指定order by子句。

mysql索引原理與用法例項分析

本文例項講述了mysql索引原理與用法。分享給大家供大家參考,具體如下 首發日期 2018 04 14 更多關於mysql相關內容感興趣的讀者可檢視本站專題 mysql索引操作技巧彙總 mysql常用函式大彙總 mysql日誌操作技巧大全 mysql事務操作技巧彙總 mysql儲存過程技巧大全 及 ...

MYSQL用法 九 索引用法

什麼是索引 索引時一種特殊的檔案,他們包涵著對資料表裡所有記錄的引用指標。當對資料表記錄進行更新後,都會對索引進行重新整理。索引會占用相當大的空間,應該只為經常查詢和最經常排序的資料列建立索引。索引型別 普通索引 這是最基本的索引型別,而且它沒有唯一性之類的限制。普通索引可以通過以下幾種方式建立 i...

索引和索引例項分析

資料庫索引,是資料庫管理系統中乙個排序的資料結構,以協助快速查詢 更新資料庫表中資料。就像我們以前用的新華字典的目錄一樣,能幫助我們快速查詢到某乙個字。分類角度 索引名稱 資料結構 b 樹,hash索引,r tree等 儲存層面 聚簇索引,非聚簇索引 邏輯層面 主鍵索引,普通索引,復合索引,唯一索引...