SQL FROM大表和小表的順序, %位置的性能影響


1.B

 
ORACLE 的解析器按照從右到左的順序處理FROM子句中的表名,FROM子句中寫在最后的表(基礎表 driving 
 
table)將被最先處理,在FROM子句中包含多個表的情況下,你必須選擇記錄條數最少的表作為基礎表。如
 
果有3個以上的表連接查詢, 那就需要選擇交叉表 (intersection table)作為基礎表, 交叉表是指那個被
 
其他表所引用的表.
 
2.如果有索引, 按照性能高低排序 C>A>B, 如果沒有索引, 則根據返回數據量判斷性能高低
 
我們看有索引的情況:
針對 DB2和Oracle數據庫, 請看摘自IBM的文檔:

General READ SQL optimization for DB2 and Oracle

These techniques apply to both DB2 and Oracle, however, the rules appear to yield a better response time on DB2.

  1. Avoid using wildcard (%) at the beginning of a predicate.
    The predicate  LIKE '%abc' causes full table scan. For example: SELECT * FROM TABLE1 WHERE COL1 LIKE '%ABC'

    This is a known performance limitation in all databases.

 
針對 SQL Server數據庫, 請看摘自Microsoft的文檔:
SR0005: Avoid using patterns that start with “%” in LIKE predicates
Rule Description:
You could cause a table scan if you use a WHERE clause that contains a LIKE predicate such as '%pattern string' to search for text that can occur anywhere in a column.
How to Fix Violations:
To resolve this issue, you should change the search string so that it starts with a character that is not a wildcard (%), or you should create a full-text index.
 
其他數據庫暫時沒有去考證
 
由此看出A,B都會造成full table scan, C不會, 則C肯定比A,B快
 
以下是一段測試數據:

select *
from
 dbo.v_R_System
where
 NETBIOS_NAME0 = 'COMPUTER'

select *
from
 dbo.v_R_System
where
 NETBIOS_NAME0 LIKE 'COMPUTER'

select *
from
 dbo.v_R_System
where
 NETBIOS_NAME0 LIKE 'COMPUT%'

select *
from
 dbo.v_R_System
where
 NETBIOS_NAME0 LIKE '%COMPUT%'

When you hit CTRL+L to get the execution plan, for each of these, and mouse-over the operator on the far left, you'll see the following:

 

Notice, the first query uses = instead of LIKE.  It's got the lowest cost and uses an INDEX SEEK.  Very fast and efficient..What we would expect.

The second query uses LIKE, and no wildcards.  The cost is still pretty low and it uses an INDEX SEEK. 

The third query uses LIKE, and a wildcard, but doesn't START with a wildcard.  The cost is the same as the second and still uses INDEX SEEK.

The fourth query however, uses LIKE and starts with a wildcard.  It still uses an index, but the cost is higher and it's an INDEX SCAN so it's going to be less efficient and slower.

 
再來看A和B, A是匹配以TEST字段為后綴的數據, B是匹配以TEST字段為后綴的以及包含TEST字段的數據, 則A的數據返回量最多跟B相等, 所以A的性能高於B


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM