查找使用SQL接受的朋友请求的一小部分?

时间:2017-05-21 03:06:51

标签: mysql sql

我有一个社交网站的两个表 - 一个包含发送的所有好友请求的发送者和接收者的名称,另一个包含所有接受的好友请求的发送者和接收者的名称。我创建了一个虚拟数据库,其中包含以下内容 -

CREATE TABLE requested ( sender text(10), receiver text(10) );
INSERT INTO requested (sender, receiver) VALUES ('tom', 'jerry');
INSERT INTO requested (sender, receiver) VALUES ('tom', 'adam');
INSERT INTO requested (sender, receiver) VALUES ('tom', 'alice');
INSERT INTO requested (sender, receiver) VALUES ('anne', 'jack');
INSERT INTO requested (sender, receiver) VALUES ('anne', 'bill');

CREATE TABLE accepted ( sender text(10), receiver text(10) );
INSERT INTO accepted (sender, receiver) VALUES ('tom', 'jerry');
INSERT INTO accepted (sender, receiver) VALUES ('tom', 'alice');
INSERT INTO accepted (sender, receiver) VALUES ('anne', 'jack');

如何显示每个用户接受的好友请求的比例?对于这些表格,我希望看到类似的内容 -

tom | 0.6666
anne | 0.5

2 个答案:

答案 0 :(得分:1)

SELECT 
      sender, 
      count(*) / (SELECT count(*) FROM requested 
                                  WHERE requested.sender = accepted.sender) as 'ratio' 
    FROM accepted group by sender

SELECT 
      sender, 
      (SELECT count(*) FROM accepted 
                       WHERE requested.sender = accepted.sender) / count(*) as 'ratio' 
    FROM requested group by sender

最重要的一个会忽略没有至少一个回复的发件人。底部查询将显示这些。

答案 1 :(得分:0)

在两个表之间使用外部联接,以便从“请求”表中获取所有行,并仅获取“已接受”表中的匹配行:

select
    r.sender,
    r.receiver,
    sum(case when a.sender is not null then 1 else 0 end)/count(*) as fraction
from
    requested as r
    left join accepted as a
        on a.sender=r.sender
        and a.receiver=r.reciever
group by
    r.sender,
    r.receiver;