有一个社交网络,每个用户都可以重新发布其他用户的帖子。你的帖子每10个转发你得到一份礼物。有两个表:gifts
和repost_history
,请参阅下面的方案。
问题: 如何编写一个查询来计算系统中每个用户需要多少礼物?
=========
= gifts =
=========
id // PK
user_id // id of user which received a gift
amount // amount of gifts (bonuses), may be + or -
type // type of a gift. The only type we're interested in is 'REPOST_TYPE'
==================
= repost_history =
==================
id // PK
user_id // id of a user which did repost
owner_id // id of a user whose post was reposted
查询算法:
1)查找每个用户的总转发次数
SELECT owner_id, COUNT(owner_id) FROM repost_history GROUP BY owner_id;
2)查找每位用户的REPOST_TYPE
份礼物总额
SELECT user_id, COUNT(amount) FROM gifts WHERE type = 'REPOST_TYPE' GROUP BY user_id;
3)根据owner_id = user_id
4)来自基于第3步结果的(user_id,gift_to_grand_count)结果集。 <gift_to_grand_count> = (<reposts_of_user> / 10) - <user_repost_gifts_amount>
我的解决方法: 1-3步骤实现(不工作,因为我不知道如何将子查询结果设置为变量)。如何使它工作并做第4步?
(
SELECT owner_id, COUNT(owner_id) AS reposts_count
FROM reposts_history
GROUP BY owner_id
AS user_reposts
)
INNER JOIN (
SELECT user_id, COUNT(amount) AS gifts_count
FROM gifts
WHERE type = 'REPOST_GIFT'
GROUP BY user_id
AS user_gifts
)
ON user_reposts.owner_id = user_gifts.user_id
为简单起见,我们假设我们想要在每个第3个转贴(而不是每个第10个转发)上赠送礼物
礼物 - 您可以看到user_id=1
已获赠1件REPOST_TYPE
礼物。我们对他花了多少礼物不感兴趣。
id | user_id | amount | type |
1 | 1 | 1 | 'REPOST_TYPE' |
2 | 1 | 2 | 'OTHER_TYPE' |
3 | 1 | -1 | 'REPOST_TYPE' |
4 | 2 | 1 | 'REPOST_TYPE' |
reposts_history - 您可以看到其他用户重新发布了用户owner_id=1
6次。
id | user_id | owner_id | another columns...
1 | 2 | 1 |
2 | 3 | 1 |
3 | 4 | 1 |
4 | 5 | 1 |
5 | 2 | 1 |
6 | 6 | 1 |
6 | 13 | 2 |
所以user_id=1
应该获得<total_reposts> / 3 - <already_granted_gifts_amount> = 6 / 3 - 1 = 1
个礼物。
我想获得系统中的所有用户:
user_id | gifts_to_grant |
1 | 1 |
2 | 0 |
..........
答案 0 :(得分:1)
您需要一个外部联接,以便找到值得赠送但尚未收到礼物的用户:
select
b.ownerid as userid,
b.rebets_count,
b.rebets_count / 10 as gifts_expected,
coalesce(g.gifts_count, 0) as gifts_received,
b.rebets_count / 10 - coalesce(g.gifts_count, 0) as gifts_missing
from
(
select owner_id, count(*) as rebets_count
from bets
group by owner_id
) b
left join
(
select user_id, count(*) as gifts_count
from gifts
where type = 'REBET_GIFT'
group by user_id
) g on g.user_id = b.owner_id;