1.想要檢索一行或者幾行時泳桦,用where子句過濾行
select * from customer:
select * from customer where customer_id in (1,2); 將要檢索的行限制在需要的行中
2.使用表連接而不是多個查詢
select name,product_type_id from products where product_id=1;
select name from product_types where product_type_id = 1;
select p.name,pt.name from products p,product_types pt where p.product_type_id = pt.product_type_id and p.product_id=1;
3.執(zhí)行連接時使用完全限定的列引用
select p.name,pt.name,description,price from products p,product_types pt where p.product_type_id =pt.product_type_id and p.product_id=1;
select p.name,pt.name,p.description,p.price from products p,product_types pt where p.product_type_id =pt.product_type_id and p.product_id=1;
省的數(shù)據(jù)庫再去兩個表搜了晚吞,非智能,只能人為的干預
4.使用case表達式而不是多個查詢
需要對表的相同行執(zhí)行許多次計算
select count(*) from products where price <13;
select count(*) from products where price between 13 and 15;
select count(*) from products where price > 15;
select?
? ? ?count(case when price <13 then 1 else null end) low,
? ? ?count(case when price between 13 and 15 then 1 else null end)med,
? ? ?count(case when price >15 then 1 else null end) high from products;
case 表達式中可以使用重疊的范圍和不同的函數(shù)
5.添加表索引
5.1 何時創(chuàng)建B-樹索引埋酬,當單個查詢檢索的行數(shù)小于等于表總行數(shù)的10%時哨啃,建立B-樹索引。
oracle數(shù)據(jù)庫會自動為表的主鍵和包含在唯一約束中的列創(chuàng)建B-樹索引
當執(zhí)行分層查詢(包含connect by的查詢時)應(yīng)該為start with和connect by 子句引用的列添加B-樹索引
5.2何時創(chuàng)建位圖索引
包含小范圍值写妥,在where子句中頻繁出現(xiàn)的列加位圖索引拳球,此索引用于數(shù)據(jù)倉庫,讀的多珍特,改的少(并發(fā)修改很少)
6.使用where而不是having
where過濾行祝峻,having子句用于過濾行組,行被分組后having才可以上場
select product_type_id ,avg(price) from products group by product_type_id having product_type_id in (1,2);? 反例
select product_type_id ,avg(price) from products where? ?product_type_id in (1,2) ? ? group by product_type_id ; 正例
7.使用union all 而不是union
union all兩個表的所有行扎筒,包括重復行
union是所有不重復的行(需要刪除重復的行莱找,費時間)
select product_id,product_type_id ,name from products union select prd_id,prd_type_id,name from more_products;去了重復
select product_id,product_type_id ,name from products union? all select prd_id,prd_type_id,name from more_products;會重復
個人覺得視使用場景而定
8.使用exists而不是in
in用于檢索一個值是否包含在列表中,查的是實際的值
exists用于檢查子查詢返回行的存在性
select product_id,name from products where product_id in (select product_id from purchases);
select product_id,name from products outer where exists (select product_id from purchases inner where inner.product_id=outer.product_id);
9.使用exists而不是distinct
distinct是去重嗜桌,在排除重復行之前要對檢索到的行排序
select distinct pr.product_id,pr.name from products pr ,purchases pu where pr.product_id=pu.product_id;
select product_id,name from products outer where exists (select 1 from purchases inner where inner.product.product_id=outer.product_id);
10.sql的緩存
先查緩存奥溺,但是sql語句必須是一模一樣才可以,字母大小寫骨宠,空格浮定,字符等必須是一模一樣才可以,緩存的命中率
綁定變量诱篷,也可以命中緩存
begin
:v_product_id:=1;
end;
select * from products where product_id = :v_product_id;
begin
:v_product_id:=2;
end;
select * from products where product_id = :v_product_id;
這樣的兩個是同一個sql語句壶唤,通過變量的賦值來命中緩存,提高性能