简体   繁体   English

将select语句的值设置为变量并在更新查询mysql中使用

[英]Set value of select statement into variable and use in update query mysql

What I'm trying to achieve is to update a column on the database based on the result of a select query in mysql. 我想要实现的是基于mysql中的select查询结果更新数据库上的列。

For example: 例如:

SELECT id, value, t_stamp FROM table_name ORDER BY id DESC Limit 1

then the value of the SELECT statement say would be 那么SELECT语句的值就是

id    value    t_stamp

1      apple    2013-01-01

2      dog      2013-01-01

so then the value of the SELECT would be from 2 right. 因此SELECT的值将从2开始。 but i want to get the value of the 'value' column and use that as a parameter for the UPDATE 但我想获取“值”列的值并将其用作UPDATE的参数

UPDATE table_name SET newvalue = value_from_select

so then value of the newvalue would be dog. 因此newvalue的值将是dog。

How can I do this in Mysql? 如何在Mysql中做到这一点?

Is this what you are looking for? 这是你想要的?

select id,@b:=value,t_stamp from table_name ORDER BY id DESC Limit 1;

UPDATE table_name SET value = @b where id=2;

you can use @var:= operator to store the retrieved data in a user defined variable which can later be substituted in an update query as shown above. 您可以使用@var:=运算符将检索到的数据存储在用户定义的变量中,该变量以后可以在更新查询中替换,如上所示。 You can also use SET @a = 0 or 0.0 or '' to define its type before retrieving data in order to avoid confusion. 您也可以在检索数据之前使用SET @a = 0或0.0或''定义其类型,以避免混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM