mysql中in和exist的區別


mysql中in和exists的區別

-- in寫法
select * from A where A.id in (select bid from  B ) and A.name in (select bname from  B ) ;

-- exits寫法
select * from A where  EXISTS (select 1 from  B.bid = A.id );

  • 區別1
    當B表的數據遠大於A表的數據 exits的效率更高(B表大,用exits)
    當B表的數據遠小於A表的數據 in的效率更高(B表小,用in)
    當B表的數據和A表的數據差不多 in/exits效率基本一致

  • 區別2
    --  如果關聯的字段是多個的時候用exits效率更高,可以減少B表的查詢次數,提高效率

    --例子:除了通過id,還需要name字段來進行關聯

    -- 使用in來完成會查詢B表多次,效率低
    select * from A where A.id in (select bid from  B ) and A.name in (select bname from  B ) ;

    -- 使用existis來完成,可以減少B表的查詢次數,提高效率
    select * from A where  EXISTS (select 1 from  B.bid = A.id and B.bname = A.name )


免責聲明!

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



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