MySQL记录符合条件

时间:2010-09-20 08:43:18

标签: mysql optimization

我需要获得表«帖子»的记录数,其中投票> = 5来创建分页。

表:

表«帖子»:user_id,post_n,visibility,type

能见度值:0,1,2;类型值:'text','photo'...(它是枚举字段,有6个值)

表«投票»:vote_n,post_n,voter_id,投票

投票值:-1或1

查询:

SELECT post_n, (SELECT SUM(vote) FROM votes WHERE votes.post_n=posts.post_n)AS votes
FROM posts WHERE visibility=2 AND type='text' HAVING votes>=5

时间0.4039

是否可以对其进行优化?

1 个答案:

答案 0 :(得分:0)

我认为如果没有子查询,你会得到更好的结果。您可以使用GROUP BY

执行此操作
SELECT p.post_n AS post_n, SUM(v.vote) AS votes
FROM posts p
INNER JOIN votes v ON (v.post_n = p.post_n)
WHERE p.visibility = 2 AND p.type = 'text'
GROUP BY p.post_n
HAVING SUM(v.vote) >= 5