Oracle中使用join表连接查询代替 in和not in 查询
转载
首先,在oracle中效率排行:表连接>exist>not exist>in>not 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