MySQL SQL語句優化

2021-08-15 07:26:03 字數 1652 閱讀 6921

檢視表定義:show create table users;

檢視表的索引:show index from users;

你要獲取第乙個表的所有資訊,你說全表掃瞄快呢還是索引掃瞄快呢?所以當你查詢庫(包括left join中的臨時庫)的所有資訊時,資料庫會選擇最優方法——全表掃瞄!!!

/*s表dept_id、name,及d表的id_o均加了索引!!!*/

/*(只使用了d表的索引)導致只有s表內容全的,d表只現示s.name='zs'對應的值 */

explain

select s.name,d.name from student s left join dept d on s.dept_id = d.id_o and s.name='zs'

/*(使用了雙表的索引),很值得記住的寫法left join on where!!!*/

explain

select s.name,d.name from student s left join dept d on s.dept_id = d.id_o where s.name='zs'

對查詢進行優化,應盡量避免全表掃瞄

1. 首先應考慮在 where 及 order by 涉及的列上建立索引,使用選擇率高的字段建索引。

2. 不使用 != 或 <> 操作符all。

3. 不使用 is null 或 is not null all

可以在num上設定預設值0,確保表中num列沒有null值,然後這樣查詢:

select id from t where num=0

4. 不使用 orall

可以這樣查詢:

select id from t where num=10

union all

select id from t where num=20

5. 如果like是以『%』開始all

6. 不使用 in 和 not in  all

對於連續的數值,能用 between 就不要用 in 了:

select id from t where num between 1 and 3

7. 不在where進行函式運算all

8. 不使用復合索引的第一部分(即最左字首原則)all

9. 建議 exists 代替 in (注意兩邊表的數量多少)

exists用於檢查子查詢是否至少會返回一行資料,該子查詢實際上並不返回任何資料,而是返回值true或false

exists(包括 not exists )子句的返回值是乙個bool值。 exists內部有乙個子查詢語句(select ... from...), 我將其稱為exist的內查詢語句。

其內查詢語句返回乙個結果集。 exists子句根據其內查詢語句的結果集空或者非空,返回乙個布林值。

一種通俗的可以理解為:將外查詢表的每一行,代入內查詢作為檢驗,如果內查詢返回的結果取非空值,則exists子句返回true,這一行行可作為外查詢的結果行,否則不能作為結果。

10. 索引並不是越多越好,可以提高select 的效率,但同時也降低了 insert 及 update 的效率,因為 insert 或 update 時有可能會重建索引(b+tree的insert導致樹結構變化)

MySQL SQL 語句優化方法

對查詢進行優化,應盡量避免全表掃瞄,首先應考慮在 where 及 order by 涉及的列上建立索引.導致索引失效的操作 應盡量避免在 where 子句中使用 或 操作符,否則將引擎放棄使用索引而進行全表掃瞄.應盡量避免在 where 子句中對字段進行 null 值判斷,否則將導致引擎放棄使用索引...

MySQL SQL語句優化explain關鍵字

explain select from score where cno 3 105 and degree select degree from score where sno 109 id select type table type possible keys keykey len refrows...

MySQL SQL語句和索引優化

索引優化 2.合理使用索引 慢查詢explain關鍵字 子查詢 select from customerinfo where customerid notin select customerid from salesinfo 連線查詢 select from customerinfo left jo...