MySQL:计数高于平均值
MySQL: where count is higher than average
我想 select 拥有特定关注者的用户的帖子高于总体平均值(与其他用户相比)
问题是当我使用 AVG()
时它限制了通过的 posts/users 的数量,但我不能使用 GROUP BY j.id
因为它会打破平均计数并且 WHERE j2.fCount >= j2.oAvg
停止正常工作
这是我的代码
SELECT * FROM (
SELECT j.*, ROUND(AVG(j.fCount)) as oAvg
FROM (
SELECT p.id , COUNT(fCount.id) as fCount
FROM `post` p
LEFT JOIN `table` table ON ...
LEFT JOIN `user` user ON ....
LEFT JOIN `follow` fCount ON fCount.user_id=user.id AND fCount.follow_id=table.ids
WHERE p.user_id=fCount.user_id
group by p.id
) j
---- > `GROUP BY j.id` - BREAKS THE AVERAGE BELOW
) j2
WHERE j2.fCount >= j2.oAvg
谢谢 :)
因为您要与平均值进行比较,所以您可能需要像这样进行两次内部查询。
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
只需将 j1 和 j2 的内部查询替换为您的 j
如果你只想运行内部查询,一旦你可以使用用户定义的变量来总计你的计数除以计数来计算你自己的平均值,就像这样
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
我想 select 拥有特定关注者的用户的帖子高于总体平均值(与其他用户相比)
问题是当我使用 AVG()
时它限制了通过的 posts/users 的数量,但我不能使用 GROUP BY j.id
因为它会打破平均计数并且 WHERE j2.fCount >= j2.oAvg
停止正常工作
这是我的代码
SELECT * FROM (
SELECT j.*, ROUND(AVG(j.fCount)) as oAvg
FROM (
SELECT p.id , COUNT(fCount.id) as fCount
FROM `post` p
LEFT JOIN `table` table ON ...
LEFT JOIN `user` user ON ....
LEFT JOIN `follow` fCount ON fCount.user_id=user.id AND fCount.follow_id=table.ids
WHERE p.user_id=fCount.user_id
group by p.id
) j
---- > `GROUP BY j.id` - BREAKS THE AVERAGE BELOW
) j2
WHERE j2.fCount >= j2.oAvg
谢谢 :)
因为您要与平均值进行比较,所以您可能需要像这样进行两次内部查询。
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 只需将 j1 和 j2 的内部查询替换为您的 j
如果你只想运行内部查询,一旦你可以使用用户定义的变量来总计你的计数除以计数来计算你自己的平均值,就像这样
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