代码之家  ›  专栏  ›  技术社区  ›  sardok

为什么使用子查询的联接性能更好

  •  0
  • sardok  · 技术社区  · 3 年前

    我有三张桌子;

    Users -> id (indexed, big int)
    Accounts -> uuid (varchar, indexed), user_id (indexed, big int)
    Trades -> uuid (varchar, indexed), account_uuid (varchar, not indexed)
    

    它们都没有定义外键。

    我想通过用户id获取交易条目。

    我可以通过以下查询获得所需信息

    查询1:

    select t.account_uuid
    from trades t
    inner join accounts acc on acc.uuid = t.account_uuid
    inner join users u on acc.user_id = u.id
    where u.id = 1;
    

    大约需要4秒。

    问题2:

    select t.account_uuid
    from trades t
    where t.account_uuid in (select acc.uuid from accounts acc where acc.user_id = 1);
    

    大约需要4秒。

    问题3:

    select t.account_uuid from trades t
    inner join (
        select acc.uuid
        from accounts acc
        where acc.user_id = 1
        group by acc.uuid
    ) as acc on acc.uuid = t.account_uuid;
    

    耗时约1.3秒。

    我试图解释为什么最后一个查询比其他查询更快?如果我删除 group by acc.uuid 从上一个查询开始,它执行的操作与其他查询相同。

    0 回复  |  直到 3 年前
    推荐文章