简体   繁体   English

始终在 SQL 中的最后一个条目之后将新数据插入表中

[英]Insert new data into table always after last entry in SQL

I have several tables with a time unix and time mez column for identification.我有几个表,时间为 unix 和时间 mez 列用于识别。 Those will be continuously filled with new data (every 60 seconds to be precise).这些将不断填充新数据(准确地说是每 60 秒)。 I created a table, let's call it new_table from data of those tables.我创建了一个表,我们从这些表的数据中将其称为 new_table。 Now I want to update this new_table.现在我想更新这个 new_table。 But only with data of the other tables which are newer than the last entry of new_table.但仅适用于比 new_table 的最后一个条目更新的其他表的数据。

So I don't have to overwrite new_table or collect all the data starting from row 1 again, since it supposed to run for years.所以我不必覆盖new_table或再次收集从第 1 行开始的所有数据,因为它应该运行多年。

I tried some INSERT or UPDATE but I can't get my head around on how to define the SELECT and WHERE condition on which data should be updated.我尝试了一些 INSERT 或 UPDATE 但我无法理解如何定义 SELECT 以及应更新数据的 WHERE 条件。 I'm very inexperienced in SQL.我对SQL非常缺乏经验。 Thanks in advance!提前致谢!

See the following code on how I created new_table:请参阅以下关于我如何创建 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;

the most recent row in new_table can be found with可以找到new_table中的最新行

SELECT max(time_unix) FROM new_table

Knowing that, you can probably figure out how to get the new data.知道了这一点,您可能会弄清楚如何获取新数据。 I'm not sure if you really want to create a new table each time you do this.我不确定您是否真的想在每次执行此操作时都创建一个新表。 TRUNCATE may be useful for you, but I think you want something like this: 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)

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

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