1

How can I use user defined variables in a MySql update statement? By user defined variables, i'm referring to the @v:=.

The statement below works fine without the user defined variables, but not with them.

update amga a left join amgb b on a.itemTempId = b.itemTempId
set @i:= concat(a.itemCountry,'-',a.id), a.itemId = @i, b.itemId = @i 
where a.itemId is null or b.itemId is null;

I'll be using this with php PDO later.

This works, but does use user defined variables

update amga a left join amgb b on a.itemTempId = b.itemTempId
set a.itemId = concat(a.itemCountry,'-',a.id), b.itemId = concat(a.itemCountry,'-',a.id) 
where a.itemId is null or b.itemId is null;

1 Answer 1

2

Try following syntax:

update amga a left join amgb b on a.itemTempId = b.itemTempId
set a.itemId = (@i:= concat(a.itemCountry,'-',a.id)), b.itemId = @i 
where a.itemId is null or b.itemId is null;

SQLFiddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

You can avoid the user variable here AFAIK, with set a.itemId = concat(a.itemCountry,'-',a.id), b.itemId = a.itemId since MySQL updates use the updated values in the next "SET" assignments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.