我有三张桌子;
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
从上一个查询开始,它执行的操作与其他查询相同。