Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MYSQL多组by和max_Mysql_Sql_Sum_Max - Fatal编程技术网

MYSQL多组by和max

MYSQL多组by和max,mysql,sql,sum,max,Mysql,Sql,Sum,Max,这是一张名为posts_vots的表格 id|discussion_id|post_id|user_id|vote_sign| __________________________________________ 1 | 1 | 1 | 1 | 1 | 2 | 1 | 1 | 2 | -1 | 3 | 1 | 2 | 3 | 1 | 4 | 1

这是一张名为posts_vots的表格

id|discussion_id|post_id|user_id|vote_sign|
__________________________________________
1 |      1      |   1   |   1   |     1   |
2 |      1      |   1   |   2   |    -1   |
3 |      1      |   2   |   3   |     1   |
4 |      1      |   2   |   4   |     1   |
5 |      2      |   3   |   1   |    -1   |
6 |      2      |   4   |   2   |     1   |
我想用这些结果创建一个视图:

discussion_id|post_id|score
      1      |   2   | 2
      2      |   4   | 1
与:

  • post_id是得分最高的帖子
  • 分数是总和(投票号)
我和group by和max一起折磨我的心,但我找不到办法=(

如果有人有主意


谢谢;)

首先使用子查询计算分数并为每个讨论id选择最大分数。然后
加入结果集以获得每个讨论id的最大分数的帖子

select t1.*
from (select discussion_id,post_id,sum(vote_sign) as score
      from posts_votes
      group by discussion_id,post_id) t1
join (select discussion_id,max(score) as maxscore 
      from (select discussion_id,post_id,sum(vote_sign) as score
            from posts_votes
            group by discussion_id,post_id) t
      group by discussion_id) t2 
on t1.discussion_id = t2.discussion_id and t1.score = t2.maxscore

这里是与您的问题相对应的查询

select
  discussion_id, 
  max(post_id) as max_post_id,
  sum(vote_sign) as score
from
  posts_votes 
group by
  discussion_id;

这恰好为示例数据提供了正确的解决方案,但是max(post_id)并不总是返回正确的post。是的。这是必需的@草莓..如果使用其他支持窗口功能的dbms,它会更容易。耶!非常感谢。这很好,只有当两个项目的分数相同时才有缺点,但我会用代码来处理它!
select
  discussion_id, 
  max(post_id) as max_post_id,
  sum(vote_sign) as score
from
  posts_votes 
group by
  discussion_id;
select SUBSTRING_INDEX(GROUP_CONCAT(post_id ORDER BY sm DESC), ',', 1)  AS top_post, discussion_id, max(score) as score
from (
    select discussion_id, post_id, sum(vote_sign) as score
    from posts_votes
    group by post_id, discussion_id
) c
group by discussion_id