在不同的密钥上连接两次相同的表

时间:2011-09-22 13:05:51

标签: mysql sql join

我有两张表accountssubs 第一个表格包含id,第二个表格包含字段idrequester_account_idgrabber_account_id

我想要计算一个帐户制作了多少个子请求,以及他做了多少抓取(基于requester_account_id/grabber_account_id是否填充了id

在一个查询中

输出:

+------------+----------------+-----------------+
| account_id | subs_requested | subs_grabbed    |
+------------+----------------+-----------------+
|  1         | 4              | 3               |
|  3         | 2              | 1               |
+------------+----------------+-----------------+

4 个答案:

答案 0 :(得分:5)

使用类似

的内容
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 s1subs as s2,每次都加入不同的字段....

关于效率的注意事项:我不确定,但我相信这个解决方案比子查询解决方案更快,但没有经过测试(至少它不会慢)。我总是喜欢left join而不是子查询。

答案 1 :(得分:2)

这应该有效:

SELECT a.account_id,
(SELECT COUNT(*) FROM subs WHERE requester_account_id=a.account_id) AS subs_requested,
(SELECT COUNT(*) FROM subs WHERE grabber_account_id=a.account_id) AS subs_grabbed
FROM accounts a

答案 2 :(得分:1)

据我了解你在寻找什么,它会是这样的:

select
    a.id as account_id,
    count(distinct sr.id) as requests,
    count(distinct gr.id) as grabs
from
    accounts a
left outer join subs sr
    on sr.requester_account_id = a.id
left outer join subs gr
    on gr.grabber_account_id = a.id

有时候,我在使用左边连接上的聚合函数时遇到了奇怪的问题,所以这是另一种方式:

select
    a.id as account_id,
    (select count(distinct sr.id) from subs sr where sr.requester_account_id = a.id) as requests,
    (select count(distinct gr.id) from subs sr where gr.grabber_account_id = a.id) as grabs
from 
    accounts a

答案 3 :(得分:0)

如果需要,您只能加入子表一次(不确定这表现得更好)

select 
acc.id
sum(if(sub.requester_account_id = acc.id, 1, 0)) as req,
sum(if(sub.grabber_account_id = acc.id, 1, 0)) as grab
from subs sub, accounts acc
where sub.requester_account_id = acc.id or sub.grabber_account_id = acc.id
group by acc.id