这是后续行动: Dynamic minimum value for specfic range (mysql)
我确实有查询通过SELECT命令获取第三列(过去3天中最低的一天)“Low_3_days”:
-----------------------------------------
| Date | Unit_ | Lowest_in_last_|
| | price | 3_days |
|----------------------------------------
| 2015-01-01 | 15 | 15 |
| 2015-01-02 | 17 | 15 |
| 2015-01-03 | 21 | 15 |
| 2015-01-04 | 18 | 17 |
| 2015-01-05 | 12 | 12 |
| 2015-01-06 | 14 | 12 |
| 2015-01-07 | 16 | 12 |
|----------------------------------------
select S.Date,Unit_price,
(select S.Date, Unit_price,
(SELECT min(s2.Unit_Price)
FROM table s2
WHERE s2.DATE BETWEEN s.DATE - interval 3 day and
s.DATE - interval 1 day
) as min_price_3_days
FROM table S;
我的新挑战是 - 使用UPDATE-SET-WHERE的最佳方法是什么,这样我就可以将(“Lowest_in_last_3_days”)值添加到表中的新列(而不是通过SELECT向我显示临时结果) 。
通过遵循UPDATE-SET-WHERE语法,查询将是:
UPDATE table
SET min_price_3_days =
(select S.Date, Unit_price,
(SELECT min(s2.Unit_Price)
FROM table s2
WHERE s2.DATE BETWEEN s.DATE - interval 3 day and
s.DATE - interval 1 day
) as min_price_3_days
但是我在构建正确的查询时遇到了困难。 对此有什么正确的解决方法?我确实认识到这个问题很难解决。
答案 0 :(得分:1)
您的UPDATE
应如下:
update table set low_3_days=
(SELECT min(Unit_Price)
FROM (select unit_price, date as date2 from table) as s2
WHERE s2.date2 BETWEEN date - interval 3 day and date - interval 1 day
);
您可以在SQLFiddle
中查看在小提琴中,我对表格和列使用了不同的名称。我不想将SQL关键字用作名称