Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

sql - UPDATE with SUM() in MySQL

My table:

ID  NAME COST  PAR  P_val  S_val
1   X    5     0    1      0
1   y    5     0    2      0
1   z    5     0    0      5
2   XY   4     0    4      4

I need to update the PAR field with the SUM(S_val), grouped by ID:

  • For ID 1 PAR should be SUM(SVAL) WHERE ID=1
  • For ID 2 PAR should be SUM(SVAL) WHERE ID=2

Expected ouput:

ID  NAME COST PAR  P_val  S_val
1   X    5     5   1      0
1   y    5     5   2      0
1   z    5     5   0      5     
2   XY   4     4   4      4

How can I UPDATE the PAR value?

My code:

UPDATE Table_Name SET PAR = (SELECT SUM(S_val) FROM Table_Name WHERE ID=1) 
FROM   Table_Name

This does not work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, you cannot update a table joined with itself in MySQL.

You'll need to create a function as a workaround:

DELIMITER $$

CREATE FUNCTION `fn_get_sum`(_id INT) RETURNS int(11)
READS SQL DATA
BEGIN
      DECLARE r INT;
      SELECT  SUM(s_val)
      INTO    r
      FROM    table_name
      WHERE   id = _id;
      RETURN r;
END $$

DELIMITER ;

UPDATE  table_name
SET     par = fn_get_sum(id)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...