finding value of column after ON DUPLICATE KEY UPDATE
Consider this statement:
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE d=d+1;
I need the value of d
.
Is it possible to obtain it without performing a further SELECT
?
There is a unique index on a,b,c
. Would this index be used for 开发者_如何学编程better performance? This table will have a large number of rows.
Assuming you will be running both queries using the same connection, You can use the LAST_INSERT_ID(expr)
function to set the current value of d
, and check the value of LAST_INSERT_ID()
together with the ROW_COUNT()
function to find out if the record was inserted or updated:
INSERT INTO table (a,b,c)
VALUES (1,2,3)
ON DUPLICATE KEY UPDATE d = LAST_INSERT_ID(d + 1);
SELECT IF(ROW_COUNT() = 2, LAST_INSERT_ID(), 0 /*default value*/) ;
You can also use session variables:
INSERT INTO table (a,b,c)
VALUES (1,2,3)
ON DUPLICATE KEY UPDATE d = @tmp := (d + 1);
SELECT IF(ROW_COUNT() = 2, @tmp, 0 /*default value*/) ;
精彩评论