標籤:mit com ble myisam order tab 相同 重複數 class
小技巧:
min/max最佳化 在表中,一般都是經過最佳化的. 如下地區表
id |
area |
pid |
1 |
中國 |
0 |
2 |
北京 |
1 |
... |
|
|
3115 |
|
3113 |
我們查min(id), id是主鍵,查Min(id)非常快.
但是,pid上沒有索引, 現在要求查詢3113地區的min(id);
select min(id) from it_area where pid=3113;//全表掃描,找出所有pid=3113的,然後求出最小的id。
試想 id是有順序的,(預設索引是升續排列), 因此,如果我們沿著id的索引方向走,
那麼 第1個 pid=3113的索引結點,他的id就正好是最小的id,強制使用主鍵索引。
select id from it_area use index(primary) where pid=3113 limit 1; //查詢出來的結果是有序的,因為索引是有序的,而又沿著索引找,掃描到了之後取一行就可以了。
| 12 | 0.00128100 | select min(id) from it_area where pid=69 |
| 13 | 0.00017000 | select id from it_area use index(primary) where pid=69 limit 1 |
改進後的速度雖然快,但語義已經非常不清晰,不建議這麼做,僅僅是實驗目的.
count() 最佳化
誤區:
1:myisam的count()非常快
答: 是比較快,.但僅限於查詢表的”所有行”比較快, 因為Myisam對總行數進行了儲存.一旦有條件的查詢, 速度就不再快了.尤其是where條件的列上沒有索引.
2: 假如,id<100的商家都是我們自我裝載的,我們想查查真實的商家有多少?
select count(*) from lx_com where id>=100; (1000多萬行用了6.X秒,就不快了)
小技巧:
select count(*) from lx_com; 快
select count(*) from lx_com where id<100; 快
select count(*) frol lx_com -select count(*) from lx_com where id<100; 快
select (select count(*) from emp) - (select count(*) from emp where empno<100)
3: group by
注意:
1:分組用於統計,而不用於篩選資料.
比如: 統計平均分,最高分,適合, 但用於篩選重複資料,則不適合.
以及用索引來避免暫存資料表和檔案排序
2: 以A,B表串連為例 ,主要查詢A表的列,
那麼 group by ,order by 的列盡量相同,而且列應該顯示聲明為A的列
4: union最佳化
注意: union all 不過濾 效率提高,如非必須,請用union all
因為 union去重的代價非常高, 放在程式裡去重.
mysql----其他小技巧