[英]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=1
和id=2
不能相等,但是id=4
和id=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
: 可以使用join
在update
语句中使用:
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.