我想从具有特定关注者的用户中选择高于总体平均值的用户(与其他用户相比)
问题是,当我使用AVG()
时,它会限制发布的帖子/用户数量,但我无法使用GROUP BY j.id
因为它会打破平均点数{{1} }停止正常工作
这是我的代码
WHERE j2.fCount >= j2.oAvg
谢谢:)
答案 0 :(得分:0)
因为您尝试与平均值进行比较,所以您可能需要两次进行内部查询。
SELECT *,
(SELECT AVG(fCount) as average FROM
(SELECT COUNT(fCount.id) as fCount
FROM post p
LEFT JOIN follow fCount ON fCount.user_id = p.user_id
GROUP BY p.id
)j1
)as average
FROM
(SELECT p2.id, COUNT(fCount2.id) as fCount
FROM post p2
LEFT JOIN follow fCount2 ON fCount2.user_id = p2.user_id
GROUP BY p2.id
)j2
HAVING fCount >= average
sqlfiddle 只需用j
替换j1和j2的内部查询如果您只想运行内部查询,一旦您可以使用用户定义的变量来累计您的计数除以计数来计算您自己的平均值
SELECT id,fCount,@sum/@count as average
FROM
(SELECT id,
fCount,
@sum := @sum + fCount as total,
@count := @count + 1 as posts
FROM
(SELECT p.id,COUNT(fCount.id) as fCount
FROM post p
LEFT JOIN follow fCount ON fCount.user_id = p.user_id
GROUP BY p.id
)j,
(SELECT @sum:=0.0,@count:=0.0)initialize
)T
HAVING fCount >= average