简体   繁体   English

MySQL-如果两个加数相同,则增加总和值

[英]MySQL - Increase a Sum Value if the two Addends are the same

Struggling a few hours on a simple MySQL update syntax . 在简单的MySQL 更新语法上苦苦挣扎几个小时。 Table 's votesum column is a sum of vote1 + vote2 column. votesum列是vote1 + vote2列的总和。 If there are several votesum values that are equal to each other ( 20 and 20 like the example below ), I need to increase the votesum by 1 for the row that has the upper vote1 value. 如果有几个彼此相等的votesum数值( 如下面的示例 ,分别为20和20 ),那么我需要为具有较高的vote1值的行将votesum增加1。

Table :

id|vote1|vote2|votesum
 1|10   |10   |20
 2|5    |15   |20
 3|2    |2    |4
 4|1    |1    |2

The MySQL update syntax I am looking for should check if maximum number of votesum is alone, or there are more equal votesum values. 我正在寻找的MySQL 更新语法应检查是否最大数目的votesum或是否有相等的表决总数值。 If there are two (or more) of them, then I need to increase value of votesum . 如果有两个(或多个),那么我需要增加votesum价值。

So after update table should look as follow: 因此更新后的表应如下所示:

id|vote1|vote2|votesum
 1|10   |10   |21
 2|5    |15   |20
 3|2    |2    |4
 4|1    |1    |2
 5|0    |2    |2

Remember that the top value of votesum are the ones that I needed to update. 请记住, votesum的最高价值是我需要更新的价值。 In the example above, id=1 and id=2 cannot be equal, but id=4 and id=5 can be equal, as I don't pay attention to those votesum values that isn't a top value. 在上面的示例中, id=1id=2不能相等,但是id=4id=5可以相等,因为我不注意那些不是最高值的votesum

I think this will do what you want: 我认为这将满足您的要求:

update table t1 join table t2 on t1.votesum = t2.votesum and t1.vote1 > t2.vote2 set t1.votesum = t1.votesum + 1 order by t1.votesum limit 1 在t1.votesum = t2.votesum和t1.vote1> t2.vote2上更新table t1联接table t2设置t1.votesum = t1.votesum + 1乘以t1.votesum限制1

The following query uses variables to calculate the incremental value: 以下查询使用变量来计算增量值:

    select t.*,
           @inc := if(@votesum = votesum, @inc + 1 , 0) as inc,
           @votesum := votesum
    from t cross join
         (select @votesum := -1, @inc := 0) const
    order by votesum desc, vote1 asc;

This can be used in an update statement, using a join : 可以使用joinupdate语句中使用:

update t join
       (select t.*,
               @inc := if(@votesum = votesum, @inc + 1 , 0) as inc,
               @votesum := votesum
        from t cross join
             (select @votesum := -1, @inc := 0) const
        order by votesum desc, vote1 asc
       ) inc
       on t.id = inc.id and inc.inc > 0
    update t.votesum = t.votesum + inc.inc;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM