V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
rodneya
V2EX  ›  程序员

问个数据库查询的问题 用 exist 和普通查询有什么区别么

  •  
  •   rodneya · Nov 12, 2020 · 1918 views
    This topic created in 1996 days ago, the information mentioned may be changed or developed.

    大概就是根据 user_id 查出 这跟人的部分 id,在根据部门 id 去找这个部门的部门经理。role_id 为 8 代表是部门经理。在所有的部门经理列表中找到对应的部门经理。 这两种写法都可以查出想要的东西,但不知道具体有什么区别,或者哪种写法更好呢

    1 ) select * from user u left join role_user r on r.user.id=u.user_id where r.role_id='8' and exist( select su.org_id from user su where su.user_id='0902' and u.org_id=su.org_id)

    2 ) select * from user u left join role_user r on r.user_id=u.user_id where r.role_id='8' and u.org_id=(select org_id from user where user_id='0802')

    2 replies    2020-11-12 18:06:15 +08:00
    MrZhaoyx
        1
    MrZhaoyx  
       Nov 12, 2020
    你这种情况是没什么区别的。
    简单来说,主表大,从表小的话用 IN(=)比较好;主表小,从表大用 exists 比较好
    wisunny
        2
    wisunny  
       Nov 12, 2020 via Android
    我咋感觉你这写法有点多余呢? user 表用了两次?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   925 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 61ms · UTC 23:22 · PVG 07:22 · LAX 16:22 · JFK 19:22
    ♥ Do have faith in what you're doing.