【发布时间】:2016-05-04 16:35:48
【问题描述】:
我有 2 个单独的查询可以正常工作。鉴于它们相似,我想将它们合并为一个高性能查询。看起来很简单,因为 where 子句是相似的。但是 sum、count 和 min 函数都适用于不同的行并妨碍了。
上下文:
- 用户可以对位置进行评分(或评分)并获得积分
- 当用户 B 首次提交分数时,用户 A 可以推荐用户 B 并获得推荐积分
- 积分在特定日期后过期
- 目标是建立一个用户排行榜以及他们在特定位置(地区/国家)的得分和推荐总分
- 位置参数用“Massachusetts”、“United States”和 scoreDateTime 到期日期的硬值填充,不幸的是在两个选择子查询中重复。
问题:
如何重新组织以下查询以组合约束?必须有一种方法可以从特定日期后特定位置的分数列表开始。唯一的麻烦是获取用户 B 的第一个得分日期,并且仅在过期日期之后才向用户 A 提供推荐积分。
select scoring.userId, scoring.points + referring.points as leaderPoints
from (
select userId, sum(ratingPoints) as points
from scores s, locations l
where s.locationId = l.locationId and
l.locationArea = 'Massachusetts' and
l.locationCountry = 'United States' and
s.scoreDateTime > '2016-04-16 18:50:53.154' and
s.userId != 0
group by s.userId
) as scoring
join (
select u1.userId, count(*) * 20 as points
from users u0
join users u1 on u0.userId = u1.userId
join users u2 on u2.referredByEmail = u1.emailAddress
join scores s on u2.userId = s.userId
join locations l on s.locationId = l.locationId
where l.locationArea = 'Massachusetts' and
l.locationCountry = 'United States' and
scoreDateTime = (
select min(scoreDateTime)
from scores
where userId = u2.userId
) and
scoreDateTime >= '2016-04-16 18:50:53.154'
group by u1.userId
) as referring on scoring.userId = referring.userId
order by leaderPoints desc
limit 10;
【问题讨论】:
标签: mysql sql performance join