2017-05-21 50 views
2

我有兩個社交網站的表格 - 一個包含發送的所有好友請求的發件人和收件人的名稱,另一個包含接受的所有好友請求的發件人和收件人的名稱。我創建了一個虛擬數據庫,內容如下 -查找使用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 
+0

你似乎沒有主鍵 - 這可能會在適當的時候出現問題 – Strawberry

+0

FWIW,我不會做一個單獨的互換表。 – Strawberry

+0

@Strawberry我同意。這個問題是從「實習面試」問題清單中取得的。 – Tim

回答

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

OR

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

頂一個我會gnore發件人,至少沒有一個回覆。底部的查詢將顯示這些。

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;