SQLite:仅当价格与最后一行不同时才进行INSERT

时间:2014-12-30 20:20:31

标签: sqlite

我有一个包含2列的SQLite简单表:

timestamp |last_price
1419873093|900.0
1419874283|900.0
1419940915|900.0
1419946324|916.58
1419946981|914.46
1419947981|800.0

我只想在价格与上一行价格不同时插入新值(我不希望连续价格相同)。我可以使用以下方式从最后一行获得价格:

SELECT last_price FROM BTC_BRL order by rowid desc limit 1;

然后我将它与新价格进行比较,但如果我可以直接在SQL语句中执行此操作,那么它会更好更快。

我尝试使用CASE WHEN,但没有成功。

谢谢!

2 个答案:

答案 0 :(得分:1)

好的,这是解决方案

解决方案是使用VIEW和TRIGGER:

1)首先我们创建一个包含最后一行的VIEW:

CREATE VIEW [BTC_BRL-VIEW] AS SELECT timestamp,last_price
FROM [BTC_BRL] order by rowid desc limit 1;

2)然后我们使用INSTEAD OF创建一个TRIGGER:

CREATE TRIGGER [BTC_BRL-TRIGGER] INSTEAD OF INSERT 
ON [BTC_BRL-VIEW]

WHEN new.last_price NOT IN (SELECT last_price FROM 
[BTC_BRL-VIEW])

BEGIN INSERT INTO [BTC_BRL] values(new.timestamp,new.last_price);
END;

3)最后我们可以INSERT:

INSERT INTO [BTC_BRL-VIEW] values(1419991328,925.47);

就是这样!只有在最后一个价格与last_price(来自VIEW)不同时才会插入。我希望它也有助于其他人;)

答案 1 :(得分:0)

SQLFiddle - Insert valid new price

只需更改@price和@when变量,它将插入与否,具体取决于' join'条件。 它只会插入一行,具体取决于:

  • 新值不等于最新值
  • 新日期必须晚于最新日期

我在调试时使用' view来简化查询 - 没有什么特别的。

如有任何问题,请发表评论。

代码在'小提琴'寻找:

SET @price = 100,
    @when1 = UNIX_TIMESTAMP('2015-01-01 11:00:00');

INSERT INTO history_price (price, whenchanged)
SELECT new_price, new_time
FROM  (SELECT
     @price AS new_price, @when1 AS new_time
       ) AS proposed_price 
       JOIN latest_price
          ON proposed_price.new_price != latest_price.price
          AND proposed_price.new_time > latest_price.whenchanged

您需要的其他内容:latest_price view:

DELIMITER $$

USE `testmysql`$$

DROP VIEW IF EXISTS `latest_price`$$

CREATE ALGORITHM=UNDEFINED DEFINER=`test`@`localhost` SQL SECURITY DEFINER VIEW `latest_price` AS 
SELECT
  `history_price`.`price`       AS `price`,
  `history_price`.`whenchanged` AS `whenchanged`,
  FROM_UNIXTIME(`history_price`.`whenchanged`) AS `whendate`
FROM `history_price`
ORDER BY `history_price`.`whenchanged` DESC
LIMIT 1$$

DELIMITER ;

您已经

的测试数据

您还可以使用相关查询,如下所示:

SET @price = 900,     @ when1 = UNIX_TIMESTAMP(' 2014-12-31 10:00:00');

INSERT INTO history_price (price, whenchanged)
SELECT new_price, new_time
FROM  (SELECT
     @price AS new_price, @when1 AS new_time
       ) AS proposed_price  
WHERE EXISTS (SELECT 1
              FROM latest_price
          WHERE proposed_price.new_price != latest_price.price
            AND proposed_price.new_time > latest_price.whenchanged)