[英]Stored procedure to update parent in MySQL
I have 2 tables for representing sensors and their values: 我有2个表来表示传感器及其值:
Unit:
id
name
last_data
Data:
id
timestamp
temperature
unit
So basically I have multiple Data
rows for each Unit
. 所以基本上我每个
Unit
都有多个Data
行。
I want to add a SP so every time I insert a Data
row, it will automatically update last_data
column in the matching parent (to point to the newly create id
. 我想添加一个SP,因此每次插入
Data
行时,它都会自动更新匹配的父级中的last_data
列(以指向新创建的id
。
pseudo code:
new_id = INSERT INTO Data (temperature, unit) VALUES (25, 1);
UPDATE Unit SET last_data = new_id WHERE id=1
Not sure how to write such procedure... 不确定如何编写这样的程序...
You can use LAST_INSERT_ID()
to get the ID of the last record that you've created within your session. 您可以使用
LAST_INSERT_ID()
来获取在会话中创建的最后一条记录的ID。
So you pseudo code would become something like: 因此您的伪代码将变为:
INSERT INTO Data (temperature, unit) VALUES (25, 1);
SET @new_id = LAST_INSERT_ID();
UPDATE Unit SET last_data = @new_id WHERE id=1
Or even shorter: 甚至更短:
INSERT INTO Data (temperature, unit) VALUES (25, 1);
UPDATE Unit SET last_data = LAST_INSERT_ID() WHERE id=1
https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id https://dev.mysql.com/doc/refman/5.7/zh-CN/information-functions.html#function_last-insert-id
This can help you to solve you problem: 这可以帮助您解决问题:
INSERT INTO Data (temperature, unit) VALUES (25, 1);
this our trigger: 这是我们的触发条件:
CREATE TRIGGER update_last_data
AFTER INSERT ON 'Data' for each row
begin
SET @last_id_in_data = LAST_INSERT_ID();
UPDATE Unit SET last_data = @last_id_in_data WHERE id=1;
END;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.