在 oracle 中效率排行,
表连接>exist>not exist>in>no in
并且使用in 查询 会有查询条件数量不能超过1000 的限制;
简单提高效率可以使用 exist 代替in
换成表连接可以更大的提高效率;
用left join (左连接) 代替 not in 和 not exist
用 inner join(内连接) 代替 in 和 exist
这样可以大大提高效率;
(1)
SELECT PUB_NAME
FROM PUBLISHERS
WHERE PUB_ID NOT IN (SELECT PUB_ID FROM TITLES WHERE TYPE = ‘BUSINESS‘)
可以改写成:
SELECT A.PUB_NAME
FROM PUBLISHERS A LEFT JOIN TITLES B ON B.TYPE = ‘BUSINESS‘ AND A.PUB_ID=B. PUB_ID
WHERE B.PUB_ID IS NULL
(2)
SELECT TITLE
FROM TITLES
WHERE NOT EXISTS (SELECT TITLE_ID FROM SALES WHERE TITLE_ID = TITLES.TITLE_ID)
可以改写成:
SELECT TITLE
FROM TITLES LEFT JOIN SALES ON SALES.TITLE_ID = TITLES.TITLE_ID
WHERE SALES.TITLE_ID IS NULL
如果保证子查询没有重复 ,IN、EXISTS的相关子查询可以用INNER JOIN 代替。
比如:
SELECT PUB_NAME
FROM PUBLISHERS
WHERE PUB_ID IN (SELECT PUB_ID FROM TITLES
WHERE TYPE = ‘BUSINESS‘)
可以改写成:
SELECT DISTINCT A.PUB_NAME
FROM PUBLISHERS A INNER JOIN TITLES B ON B.TYPE = ‘BUSINESS‘ AND A.PUB_ID=B. PUB_ID
原文:https://www.cnblogs.com/wanglichaoya/p/10389828.html