简体   繁体   English

MySQL基于日期的条件插入或更新

[英]MySQL conditional insert or update based on date

I'm trying to do something like: 我正在尝试做类似的事情:

IF EXISTS(SELECT * FROM weatherbyday WHERE DATE(DateTime) = CURDATE()) 
THEN update weatherbyday 
SET  
TempMin='[th0temp-dmin]', 
TempMax='[th0temp-dmax]'
WHERE DATE(DateTime) = CURDATE()
ELSE INSERT INTO weatherbyday (DateTime, TempMin, TempMax ) VALUES ('[YYYY]-[MM]-[DD] [hh]:[mm]:[ss]', '[th0temp-dmin]','[th0temp-dmax]' )

but IF can't be used in this syntax. 但是IF不能用于此语法。

There are plenty of answers to this sort of problem conditional on duplicate keys, but I want to use the date as a condition, which can't be a key. 对于以重复键为条件的此类问题,有很多答案,但是我想使用日期作为条件,但不能将其作为键。

Can anyone provide an elegant answer? 谁能提供一个优雅的答案?

Thank you David 谢谢大卫

What you have shown is syntax in MSSQL . 您所显示的是MSSQL中的语法。 Here's for MySQL : 这是针对MySQL

IF ((SELECT COUNT(*) FROM weatherbyday WHERE DATE(DateTime) = CURDATE()) > 0) THEN
BEGIN
    UPDATE weatherbyday 
    SET     TempMin = '[th0temp-dmin]', 
            TempMax = '[th0temp-dmax]'
    WHERE   DATE(DateTime) = CURDATE();
END;
ELSE
BEGIN
    INSERT INTO weatherbyday (DateTime, TempMin, TempMax) 
    VALUES ('[YYYY]-[MM]-[DD] [hh]:[mm]:[ss]', '[th0temp-dmin]', '[th0temp-dmax]')
END;
END IF;

One simple answer is to use an integer created from the date as the unique key. 一个简单的答案是使用从日期创建的整数作为唯一键。 Then you can use ON DUPLICATE KEY. 然后,您可以使用ON DUPLICATE KEY。 This works fine for my purpose. 就我的目的而言,这很好。

INSERT INTO weatherbyday (wdID, DateTime, TempMin, TempMax,RainDay) 
    VALUES ('[YYYY][MM][DD]', '[YYYY]-[MM]-[DD] [hh]:[mm]:[ss]', '[th0temp-dmin]', '[th0temp-dmax]','[rain0total-daysum]')
  ON DUPLICATE KEY UPDATE TempMin = '[th0temp-dmin]', TempMax = '[th0temp-dmax]',RainDay='[rain0total-daysum]'

I am using the above code to upload weather station readings using Meteobridge - a hardware/software device which connects a weatherstation to the internet. 我正在使用上面的代码通过Meteobridge(将气象站连接到互联网的硬件/软件设备)上传气象站读数。 The variables are expressed in a way which the device software understands. 变量以设备软件可以理解的方式表示。 The MySQL creates a single row per day with cumulative readings - which can be extended to more columns of course. MySQL每天会创建一行具有累积读数的行-当然可以扩展到更多列。 The code will be the basis of tables for monthly and yearly records, for which Meteobridge helpfully supplies variables which contain the totals. 该代码将成为每月和每年记录的表的基础,为此Meteobridge会帮助提供包含总计的变量。

The above should be useful as an example for any application where a date based record needs to be updated if it exists, or created if not. 对于任何需要更新基于日期的记录或不创建基于日期的记录的应用程序,上面的示例都应该有用。

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

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