I have 2 tables for representing sensors and their values:
Unit:
id
name
last_data
Data:
id
timestamp
temperature
unit
So basically I have multiple Data
rows for each Unit
.
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
.
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.
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
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.