0

I'm developing an application retrieving data from a small number of sensors in an interval of 10 seconds. Those values are stored in a single-table sqlite database.

One use case of this application is to print the daily maxima of each sensor which is read.

I don't like the idea of issueing a MAX...GROUP BY day like query every time I want to retrieve those values, so I thought of maintaining a second table containing thos daily maxima.

  1. Is this the appropriate way of performing such a task?
  2. I tried writing such a trigger, but it didn't work. I'm somehow missing the ability to do the comparison among new value, and value for the current hour already in the db (which might be no value, if a new hour just started)

    CREATE TRIGGER update_maxima AFTER  INSERT ON tick
    BEGIN
        INSERT OR REPLACE INTO maxima (time, device_id, lW) 
        VALUES (
            strftime('%Y-%m-%d 00:00:00', 'now') , 
            new.device_id,
            (select case when new.lW > (select lW from maxima where device_id = new.device_id AND time = strftime('%Y-%m-%d 00:00:00', 'now'))
                then 
                    new.lW
                else 
                    (select lW from maxima where device_id = new.device_id AND time = strftime('%Y-%m-%d 00:00:00', 'now'))
                end
            )
        );
    END
    
4

1 回答 1

0
  1. 你说你更喜欢扳机;很难反驳这一点。;-)

    如果您想要一个技术原因:如果您执行最大每天查询的频率比插入一些新值的频率更高,那么触发器会更有效。

  2. 如果表中没有匹配的值,则子select lW...查询返回一个值。NULL任何与 的比较NULL都会导致NULL,这使得CASE返回ELSE值是NULL。您必须将子查询包装到IFNULL调用中。

  3. 您可以使用两个参数简化您CASE的 a :MAX

    ... VALUES (
            strftime('%Y-%m-%d 00:00:00', 'now'),
            new.device_id,
            max(new.lW,
                ifnull((SELECT lW
                        FROM maxima
                        WHERE device_id = new.device_id
                          AND time = strftime('%Y-%m-%d 00:00:00', 'now')
                       ),
                       0)
               )
        )
    
于 2013-03-20T12:05:29.623 回答