i have two table
table1:
id | time | value
----------------------------------------
1 | 2024-01-09 22:24:14 | 100
----------------------------------------
2 | 2024-01-10 22:25:14 | 200
----------------------------------------
3 | 2024-01-11 22:26:14 | 300
----------------------------------------
table2:
id | last_value
----------------------
1 | ---
----------------------
i need to update table2.lastvalue with table1 last recede (2024-01-11 22:26:14 recode value 300)
how can i do that?
i try below script
update Table1, Table2 set Table2.last_value = Table1.Value where Table2.Id=1;
But every time update in first recede (100)
2
Answers
Use Max() function to get last DATE…
With the data povided it should be 100 as the value for ID = 1 Is 100.
… If you set a condition to any of the ID-s you’ll get that ID’s VAL.
… if there where multiple ID = 1 rows in sample tbl_1 …
… then this same Update statement would result as:
Finaly if you want to get last value of all rows and update tbl_2 with that value then just remove where close from subquery and filter the tbl_2 row(s) to be updated with that value:
To get the most recent
table1.value
row you canORDER BY `time` DESC LIMIT 1
:Here’s a db<>fiddle.
Storing this redundant data is unlikely to provide any benefit over having an index on
(`time`, `value`)
. There is almost certainly a better method, depending on your specific use case.