mysql使用同一组多行的min(id)的'open'值更新组的max值

gajydyqb  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(355)

我想更新一下 open 组的最大值(id)( exchange, base_currency, quote_currency, DATE(created_at) ),使用 last 来自同一组的min(id)行。

id last open exchange base_curr quote_curr created_at

6  1.11 0.00 ex1      usd       yen        2018-07-29 03:00:00 --> update open with 1.14 (value of last from MIN(id) of group)          
5  1.09 0.00 ex1      usd       yen        2018-07-29 02:00:00
4  1.14 0.00 ex1      usd       yen        2018-07-29 01:00:00

3  0.49 0.00 ex2      yen       won        2018-07-29 03:00:00 --> update open with 0.50 (value of last from MIN(id) of group)
2  0.51 0.00 ex2      yen       won        2018-07-29 02:00:00
1  0.50 0.00 ex2      yen       won        2018-07-29 01:00:00

我知道如何获取组的所有min(id),但不知道如何使用 last 要更新的min(id)行的值 open 组的最大值(id)。
max(id)或max(created\u at)将获取组的最新行。

SELECT MIN(id) as min_id, last
FROM tickers 
WHERE DATE(created_at) = '2018-07-29' 
GROUP BY exchange, base_currency, quote_currency, DATE(created_at)
ozxc1zmp

ozxc1zmp1#

可以在子查询中计算最小值/最大值。然后用另一个 join 要从min行引入值,请执行以下操作:

update tickers t join
       (select exchange, base_curr, quote_curr, date(created_at) as created_at_date,
               max(id) as maxid, min(id) as minid
        from tickers t2
        group by exchange, base_curr, quote_curr, date(created_at)
       ) tt
       on tt.maxid = t.id join
       tickers tmin
       on tmin.id = tt.minid
    set t.open = tmin.last;

相关问题