日期:2014-05-18  浏览次数:20327 次

问个很弱智的问题,,,exists怎么代替IN,,,在线等
select * from test1 where id in(1,2,3,4,5);


我想用 exists 代替,,,请问怎么弄的,,,,(据说IN的效率低)





------解决方案--------------------
你的1,2,3,4,5要在表中才可用exists关联另一张表,并不是所有的情况都可用exists替换in的

如select * from test where id in(select id from anothertable);

些时可用exists

select * from test where exists(select 1 from anothertable where anothertable.id=test.id)
------解决方案--------------------
SQL code
WITH R AS
(
    SELECT 1 AS ID
    UNION ALL
    SELECT 2 AS ID
    UNION ALL
    SELECT 3 AS ID
    UNION ALL
    SELECT 4 AS ID
    UNION ALL
    SELECT 5 AS ID
)
SELECT * FROM test1 AS T
WHERE EXISTS (SELECT * FROM R WHERE T.ID = R.ID)