我有几个带有 time unix 和 time mez 列的表,用于识别。这些将不断地填充新数据(准确地说是每 60 秒一次)。 我创建了一个表,我们根据这些表的数据将其称为 new_table 。现在我想更新这个new_table。但仅限于比 new_table 的最后一个条目更新的其他表的数据。
因此,我不必覆盖 new_table
或再次收集从第 1 行开始的所有数据,因为它应该运行多年。
我尝试了一些 INSERT 或 UPDATE,但我无法理解如何定义应更新数据的 SELECT 和 WHERE 条件。我对 SQL 非常缺乏经验。提前致谢!
请参阅以下代码,了解我如何创建 new_table:
USE database; /* select database */
CREATE TABLE new_table
AS
SELECT
table1_1min.time_unix, table1_1min.time_mez,
/* add power consumption in kW rounded to two decimal places */
ROUND(table1.P + table2.P + table3.P, 2) AS total
FROM
table1_1min, table2_1min, table3_1min
/* make sure same time stamp is used in every row*/
WHERE
table1_1min.time_unix = table2_1min.time_unix
AND table1_1min.time_unix = table3_1min.time_unix
ORDER BY
table1_1min.time_unix;
最佳答案
可以通过以下方式找到 new_table
中的最新行
从 new_table 中选择 max(time_unix)
了解了这一点,您可能就能弄清楚如何获取新数据。我不确定您是否真的想每次执行此操作时都创建一个新表。 TRUNCATE
可能对你有用,但我认为你想要这样的东西:
INSERT INTO new_table ( time_unix, time_mez, total )
SELECT t1.time_unix, t1.time_mez, round(t1.p + t2.p + t3.p, 2) AS total
FROM table1_1min t1 JOIN table2_1min t2 ON (t1.time_unix = t2.time_unix) JOIN table3_1min t3 ON (t1.time_unix = t3.time_unix)
WHERE t1.time_unix > (SELECT max(time_unix) FROM new_table)
关于mysql - 总是在 SQL 中的最后一个条目之后将新数据插入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58101537/