MySQL:使用JOIN从cte插入到

wgx48brx  于 2023-05-16  发布在  Mysql
关注(0)|答案(1)|浏览(71)

作为我的“MySQL查询中FIRST_VALUE和LAST_VALUE失败”问题的后续,我有以下简洁的查询:

WITH cte AS (
    SELECT `Ticker`,
       MIN(`trade_ID`) AS first_trade,
       MIN(`Price`) AS min_price,
       MAX(`Price`) AS max_price,
       MAX(`trade_ID`) AS last_trade
    FROM `Hist_price`
    WHERE `Time` >= 1683469229380 AND `Time` < 1683469349380
    GROUP BY Ticker
)

SELECT cte.*, h1.price AS open_price, h2.price AS close_price
FROM cte
JOIN Hist_price AS h1 ON h1.trade_id = cte.first_trade
JOIN Hist_price AS h2 on h2.trade_id = cte.last_trade;

但实际上,我想在结果表中插入它。我尝试将最后一位(来自SELECT cte.*)替换为

INSERT INTO `calc_kline_1s` (Ticker, First_trade_id, First_trade_t, Last_trade_id, Last_trade_t, Low_p, High_p, Open_p, Close_p)                        
SELECT cte.*, h1.`price` AS open_price, h2.`price` AS close_price
FROM cte
JOIN Hist_price AS h1 ON h1.trade_id = cte.first_trade
JOIN Hist_price AS h2 on h2.trade_id = cte.last_trade;
INSERT INTO `calc_kline_1s` (Ticker, First_trade_id, First_trade_t, Last_trade_id, Last_trade_t, Low_p, High_p, Open_p, Close_p)                       
SELECT cte.Ticker,cte.first_trade,cte.first_trade_t,cte.last_trade,cte.last_trade_t,cte.min_price,cte.max_price, h1.`price` AS open_price, h2.`price` AS close_price
FROM cte
JOIN Hist_price AS h1 ON h1.trade_id = cte.first_trade
JOIN Hist_price AS h2 on h2.trade_id = cte.last_trade;
INSERT INTO `calc_kline_1s` (Ticker, First_trade_id, First_trade_t, Last_trade_id, Last_trade_t, Low_p, High_p, Open_p, Close_p)                       
VALUES (cte.Ticker,cte.first_trade,cte.first_trade_t,cte.last_trade,cte.last_trade_t,cte.min_price,cte.max_price, h1.`price` AS open_price, h2.`price` AS close_price)
FROM cte
JOIN Hist_price AS h1 ON h1.trade_id = cte.first_trade
JOIN Hist_price AS h2 on h2.trade_id = cte.last_trade;

但这两个选择都行不通我错过了什么。它通常工作正常。这次我错过了什么?

ufj5ltwl

ufj5ltwl1#

试试这个语法:

INSERT INTO calc_kline_1s
WITH cte AS (
    SELECT `Ticker`,
       MIN(`trade_ID`) AS first_trade,
       MIN(`Price`) AS min_price,
       MAX(`Price`) AS max_price,
       MAX(`trade_ID`) AS last_trade
    FROM `Hist_price`
    WHERE `Time` >= 1683469229380 AND `Time` < 1683469349380
    GROUP BY Ticker
)
SELECT cte.Ticker,cte.first_trade, cte.first_trade, cte.last_trade,cte.last_trade, cte.min_price,cte.max_price, h1.`price`, h2.`price`
FROM cte
JOIN Hist_price AS h1 ON h1.trade_id = cte.first_trade
JOIN Hist_price AS h2 on h2.trade_id = cte.last_trade;

PS:first_tradelast_trade 已经使用了两次,因为 first_trade_tlast_trade_t 不是退出
Demo here

相关问题