SQLite3:如果存在IF行,则将递增值ELSE插入新行

时间:2019-12-18 15:44:20

标签: sqlite

下午好。我尝试通过一个请求执行这种情况:我有一个表,每小时输入一个值。如果最后一次下注的日期超过1小时,我想插入一个新条目,如果在一小时内,则增加该值

示例:

+------------+-------------------+
| value      | date              |
+------------+-------------------+
|     100    |2020-08-06 12:12:12|
+------------+-------------------+
|     100    |2020-08-06 **11:11:00**|
+---------------------------------

新通知

+------------+-------------------+
|     50     |2020-08-06 **11:20:00**|
+------------+-------------------+

=>

+------------+-------------------+
| value      | date              |
+------------+-------------------+
|     100    |2020-08-06 12:12:12|
+------------+-------------------+
|     150    |2020-08-06 **11:11:00**|
+---------------------------------

需要:

IF EXISTS (SELECT * FROM energy_consumption WHERE date BETWEEN strftime('%Y-%m-%d %H:00:00', 'now') AND DATETIME('now'))
    UPDATE energy_consumption SET consumption_tarif_1 = consumption_tarif_1 + 100 WHERE date BETWEEN strftime('%Y-%m-%d %H:00:00', 'now') AND DATETIME('now')
ELSE
    INSERT INTO energy_consumption (counter_type_id, consumption_tarif_1, consumption_tarif_2, consumption_tarif_3) VALUES(1, 100, 100, 100)

但是IF - ELSE-在SQLite 3.x上不支持

我正在尝试做一个电表

1 个答案:

答案 0 :(得分:2)

使用2条语句:

UPDATE energy_consumption 
SET consumption_tarif_1 = consumption_tarif_1 + 100 
WHERE date BETWEEN strftime('%Y-%m-%d %H:00:00', 'now') AND DATETIME('now')
AND EXISTS (
  SELECT * FROM energy_consumption 
  WHERE date BETWEEN strftime('%Y-%m-%d %H:00:00', 'now') AND DATETIME('now')
);

INSERT INTO energy_consumption (counter_type_id, consumption_tarif_1, consumption_tarif_2, consumption_tarif_3) 
SELECT 1, 100, 100, 100
WHERE NOT EXISTS (
  SELECT * FROM energy_consumption 
  WHERE date BETWEEN strftime('%Y-%m-%d %H:00:00', 'now') AND DATETIME('now')
);

由于它们都包含与EXISTSNOT EXISTS互斥的条件,因此将仅执行其中的1个。