是否可以在此查询中获取overall_score的总和?

时间:2016-06-07 14:26:03

标签: php moodle

所以我有一个链接表,以及这些链接的投票表。例如,链接google.co.uk在链接表中有一条记录,然后它可以在投票表中有四条投票记录,每条记录的得分为-1,1或2。我已经完成了这个查询,它总结了每个链接的投票,但是可以对同一查询中所有链接的所有分数求和,所以用户有分数吗?

SELECT *, SUM(v.vote_score) AS overall_score 
FROM mdl_link_critic_links l 
    JOIN mdl_link_critic_votes v on l.id = v.link_id 
WHERE l.user_id = '3' 
GROUP BY l.id

结果就像

google.co.uk, user_id 3, overall_score 3
ebay.co.uk , user_id 3, overall_score 4
stackoverflow.com, user_id, 3, overall_score 10

我希望总结所有总分,所以在这种情况下,它将是17

2 个答案:

答案 0 :(得分:0)

子查询怎么样?它或多或少看起来像这样:

SELECT x.user_id, SUM(overall_score) AS user_score
FROM (
    SELECT *, SUM(v.vote_score) AS overall_score 
    FROM mdl_link_critic_links l 
    JOIN mdl_link_critic_votes v on l.id = v.link_id 
    GROUP BY l.id
) AS x
GROUP BY x.user_id;

答案 1 :(得分:0)

SELECT l.id, l.name, v.user_id, v.vote_score AS user_score, o.overall_score
FROM mdl_link_critic_links l 
JOIN mdl_link_critic_votes v ON v.link_id = l.id 
JOIN (SELECT v.link_id, SUM(v.vote_score) AS overall_score
      FROM mdl_link_critic_votes v
      GROUP BY v.link_id) o ON o.link_id = l.id