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

时间:2013-09-12 14:35:51

标签: php mysql

在一个简单的 MySQL 更新语法上挣扎了几个小时。 votesum列是vote1 + vote2列的总和。如果有多个votesum值彼此相等( 20和20,如下面的示例),我需要将votesum增加1上限vote1

表格

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

我正在寻找的 MySQL 更新语法应该检查votesum的最大数量是否单独,或者还有更多相等的票数值。如果有两个(或更多个),那么我需要增加votesum的值。

因此更新表后应如下所示:

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

请记住votesum的最高值是我需要更新的值。在上面的示例中,id=1id=2不能相等,但id=4id=5可以相等,因为我没有注意那些votesum值不是最高值。

2 个答案:

答案 0 :(得分:0)

我认为这会做你想做的事情:

在t1.votesum = t2.votesum和t1.vote1>上更新table t1加入table t2 t2.vote2 set t1.votesum = t1.votesum + 1 order by t1.votesum limit 1

答案 1 :(得分:0)

以下查询使用变量来计算增量值:

    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;

这可以在update语句中使用join

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;