MySQL在求和之前检查值是否在结果集中

时间:2015-02-22 12:37:25

标签: mysql

我有一个评论评级表,当我获取评论时,我也会获取评分,我还希望能够显示已登录用户已经投票的评论。这就是我现在正在做的事情

SELECT 
c.id, 
c.text, 
c.datetime, 
c.author, 
u.email AS author_name, 
SUM(cr.vote) AS rating, 
cr2.vote AS voted

FROM comments c 
LEFT JOIN users u ON u.id = c.author 
LEFT JOIN comments_ratings cr ON c.id = cr.comment 
LEFT JOIN comments_ratings cr2 ON c.id = cr2.comment AND cr2.user = :logged_user_id 

GROUP BY c.id ORDER BY c.id DESC

但我不喜欢我在同一张桌子上进行第二次加入。我知道它是完全有效的,但如果我能从第一次加入中得到我想要的信息,无论如何,为什么还要进行第二次?

在执行聚合函数之前,是否可以确定表user中是否存在列:logged_user_id等于comments_ratings cr的行?

P.S。:如果有人能想出一个更好的头衔,人们可以在将来找到,我也会很感激。

1 个答案:

答案 0 :(得分:3)

您可以使用条件聚合执行所需操作:

SELECT c.id, c.text, c.datetime, c.author, u.email AS author_name, 
       SUM(cr.vote) AS rating, 
       MAX(cr.user = :logged_user_id) as voted
FROM comments c LEFT JOIN
     users u
     ON u.id = c.author LEFT JOIN
     comments_ratings cr
     ON c.id = cr.comment 
GROUP BY c.id
ORDER BY c.id DESC;