我有两张桌子accounts和subs。 第一台具有id与第二表有田id,requester_account_id,grabber_account_id
accounts
subs
id
requester_account_id
grabber_account_id
我想要一个帐户进行多少次子请求以及他进行了多少次抓取的计数(基于,如果该帐户requester_account_id/grabber_account_id中填充了他的id)
requester_account_id/grabber_account_id
在一个查询中
输出:
+------------+----------------+-----------------+ | account_id | subs_requested | subs_grabbed | +------------+----------------+-----------------+ | 1 | 4 | 3 | | 3 | 2 | 1 | +------------+----------------+-----------------+
使用类似
select accounts.id, count(distinct s1.id) as num_req, count(distinct s2.id) as num_grab from accounts left join subs as s1 on accounts.id = s1.requester_account_id left join subs as s2 accounts.id = s2.grabber_account_id group by accounts.id
诀窍是使用表subs两次:subs as s1和subs as s2,每次由不同的字段联接。
subs as s1
subs as s2
关于效率的注意事项:我不确定,但是我相信这个解决方案比子查询解决方案要快,尽管没有对其进行测试(至少不会慢一些)。left join只要有可能,我总是更喜欢子查询。
left join