要求:写一个查询语句,求出谁拥有最多的好友和他拥有的好友数目。
在 Facebook 或者 Twitter 这样的社交应用中,人们经常会发好友申请也会收到其他人的好友申请。
request_accepted表得结构:
| requester_id | accepter_id | accept_date|
|--------------|-------------|------------|
| 1 | 2 | 2016_06-03 |
| 1 | 3 | 2016-06-08 |
| 2 | 3 | 2016-06-08 |
| 3 | 4 | 2016-06-09 |
表 request_accepted 存储了所有好友申请通过的数据记录,其中, requester_id 和 accepter_id 都是用户的编号。
Result Table:
| id | num |
|----|-----|
| 3 | 3 |
分析:
1.求出每个用户发送申请次数+接受申请的次数即为总好友数
SQL语句:
#1.方法1
WITH a1 AS(
SELECT requester_id AS i1,COUNT(DISTINCT accepter_id) AS r1
FROM
request_accepted
GROUP BY requester_id),
a2 AS(
SELECT accepter_id AS i1,COUNT(DISTINCT requester_id) AS r1
FROM
request_accepted
GROUP BY accepter_id
)
SELECT id,num
FROM(
SELECT a1.i1 AS id,(a1.r1+a2.r1)AS num
FROM a1,a2
WHERE a1.i1=a2.i1
UNION ALL
SELECT a1.i1 AS id,a1.r1 AS num
FROM a1
WHERE a1.i1 NOT IN(SELECT i1 FROM a2)
UNION ALL
SELECT a2.i1 AS id,a2.r1 AS num
FROM a2
WHERE a2.i1 NOT IN(SELECT i1 FROM a1)
)c1
ORDER BY num DESC
LIMIT 1;
#2.方法2
WITH a1 AS(
SELECT DISTINCT requester_id AS id FROM request_accepted
UNION ALL
SELECT DISTINCT accepter_id AS id FROM request_accepted
WHERE accepter_id NOT IN(
SELECT requester_id AS id FROM request_accepted)
)
SELECT id,(c1+c2) AS num FROM (
SELECT a1.id AS id,COUNT(DISTINCT a2.accepter_id)AS c1,COUNT(DISTINCT a3.requester_id)AS c2
FROM a1
LEFT JOIN request_accepted a2
ON a1.id=a2.requester_id
LEFT JOIN request_accepted a3
ON a1.id=a3.accepter_id
GROUP BY a2.requester_id,a3.accepter_id
ORDER BY id)a3
ORDER BY num DESC
LIMIT 1;