軟件測試中SQL代碼的優(yōu)化
1.使用索引可以快速的訪問數(shù)據(jù)庫表中的特定信息,索引是對(duì)數(shù)據(jù)庫表中一列或多列的值進(jìn)行排序的一種結(jié)構(gòu),例如 employee 表的姓名(name)列。如果要按姓查找特定職員,與必須搜索表中的所有行相比,索引會(huì)幫助您更快地獲得該信息。但是有些索引會(huì)因?yàn)?a href="" target="_self" style="word-break: break-all; color: #202859; text-decoration: none; line-height: normal !important;">SQL代碼使用不當(dāng)導(dǎo)致索引不被使用,所以在軟件測試中我們應(yīng)該糾正那些不當(dāng)?shù)腟QL代碼。以下就是sql代碼需要優(yōu)化的情況:
(1)在主鍵上建了索引,查詢條件主鍵使用or。
select *from tb_user where fd_userid=19 or fd_userid=21;這時(shí)建在fd_userid的索引將不被使用。
建議改成 where fd_userid in(19,21)
(2)盡量避免使用union。
(3)盡量避免使用not,可以用運(yùn)算符代替。
(4)隔離條件上的列,如:select * from tb_a where fd_value+=100。這時(shí)建在fd_value的索引將不被使用。
(5)盡量不單獨(dú)使用and,可以用between…and…如:where fd_time>100 and fd_time<120。可以改成fd_time between 100 and 120。
(6)盡量避免使用like的特殊形式:“%”或“_”開頭,如:“%bn” “_bn”。
(7)減少冗余條件
(8)避免使用having,也會(huì)影響字段的索引
(9)少用distinct
(10)避免使用any all,如select fd_id from tb_a where fd_id<=all(select fd_id from tb_b);可以改成<=(select min(fd_id) from tb_b+++)
(11)避免使用原生態(tài)的SQL語句,容易有sql注入。
posted on 2013-11-22 12:17 順其自然EVO 閱讀(207) 評(píng)論(0) 編輯 收藏 所屬分類: 數(shù)據(jù)庫