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
117 views
in Technique[技术] by (71.8m points)

MySQL update with if evaluation in same table

I need some help.

I got this table:

---------
ID | N1 |
---------
a    100
b    150
c    90
d    240
--------

Given 2 IDs (for example a,b) I need to do that:

If (a.n1 > b.n1) 
        
       a.n1 = b.n1
    
else 
        b.n1=a.n1;

How can I do it on MySQL?

question from:https://stackoverflow.com/questions/66066075/mysql-update-with-if-evaluation-in-same-table

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

1 Reply

0 votes
by (71.8m points)

If you're wanting to update a table in this manner you can use a Stored Procedure:

CREATE TABLE T (ID VARCHAR(5), N1 INT);
DELIMITER $$
CREATE PROCEDURE check_vals (IN a VARCHAR(5), IN b VARCHAR(5)) BEGIN 
SET @a = (SELECT N1 FROM T WHERE ID = a); 
SET @b = (SELECT N1 FROM T WHERE ID = b); 
IF @a > @b THEN UPDATE T SET N1 = @b WHERE ID = a; 
ELSE UPDATE T SET N1 = @a WHERE ID = b; 
END IF; 
END $$
DELIMITER ;

Then Just use the procedure like this:

CALL check_vals('a','b');
SELECT * FROM T;

Returns:

+----+-----+
| ID | N1  |
+----+-----+
| a  | 100 |
| b  | 100 |
| c  |  90 |
| d  | 240 |
+----+-----+

Otherwise, if your goal is to only manipulate the data in a SELECT result, then I would go with P.Salmon's answer.


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

...