使用常量值更新表

时间:2013-12-30 17:06:34

标签: mysql sql

我的表中有7列(s0,s1,s2,s3,s4,s5,s6),我想要执行以下查询:

UPDATE myTable SET s0=ROUND(s0/(s0+s1+s2+s3+s4+s5+s6)*100)/100,
  s1=ROUND(s1/(s0+s1+s2+s3+s4+s5+s6)*100)/100, 
  s2=ROUND(s2/(s0+s1+s2+s3+s4+s5+s6)*100)/100,
  s3=ROUND(s3/(s0+s1+s2+s3+s4+s5+s6)*100)/100, 
  s4=ROUND(s4/(s0+s1+s2+s3+s4+s5+s6)*100)/100, 
  s5=ROUND(s5/(s0+s1+s2+s3+s4+s5+s6)*100)/100, 
  s6=ROUND(s6/(s0+s1+s2+s3+s4+s5+s6)*100)/100;

问题是mysql更新s1然后计算s2等。

如何在sql请求中为每一行修复值(s0+s1+s2+s3+s4+s5+s6)

3 个答案:

答案 0 :(得分:3)

我相信它也应该完成这项工作(假设表有一个主键):

UPDATE myTable a
INNER JOIN 
(
  SELECT ROUND(s0/(s0+s1+s2+s3+s4+s5+s6)*100)/100 AS new_s0,
  ROUND(s1/(s0+s1+s2+s3+s4+s5+s6)*100)/100 AS new_s1, 
  ROUND(s2/(s0+s1+s2+s3+s4+s5+s6)*100)/100 AS new_s2,
  ROUND(s3/(s0+s1+s2+s3+s4+s5+s6)*100)/100 AS new_s3, 
  ROUND(s4/(s0+s1+s2+s3+s4+s5+s6)*100)/100 AS new_s4, 
  ROUND(s5/(s0+s1+s2+s3+s4+s5+s6)*100)/100 AS new_s5, 
  ROUND(s6/(s0+s1+s2+s3+s4+s5+s6)*100)/100 AS new_s6,
  pk_column 
  FROM myTable
)b ON (b.pk_column = a.pk_column)
SET a.s0 = b.new_s0, .... 

答案 1 :(得分:2)

一个明显的解决方案是:

在表格中添加列总和。 更新总和(用每行的值填充它,这是微不足道的)。 然后在查询中使用sum列(而不是s0 + s1 + s2 + s3 + s4 + s5 + s6)。 最后放下总和列。

答案 2 :(得分:1)

在STORED PROCEDURE中,您需要使用变量,例如:

CREATE PROCEDURE NameProc(
  @s0 AS INT,
  @s1 AS INT,
  @s2 AS INT,
  @s3 AS INT,
  @s4 AS INT,
  @s5 AS INT,
  @s6 AS INT
)
AS


UPDATE myTable SET s0=ROUND(@s0/(@s0+@s1+@s2+@s3+@s4+@s5+@s6)*100)/100 
      s1=ROUND(@s1/(@s0+@s1+@s2+@s3+@s4+@s5+@s6)*100)/100 
      s2=ROUND(@s2/(@s0+@s1+@s2+@s3+@s4+@s5+@s6)*100)/100