我在MySQL中有一个表,例如:
SELECT time_stamp, price,prev_price, FROM prices ORDER by time_stamp ASC;
-------------------------------
time_stamp | price | prev_price
-------------------------------
1382457241 | 23.3 | NULL
1393553097 | 14.2 | NULL
1412857868 | 16.0 | NULL
1412857965 | 201.1 | NULL
........
我希望用UPDATE语句将上一行的价格值(按时间戳排序)更新prev_price:
-------------------------------
time_stamp | price | prev_price
-------------------------------
1382457241 | 23.3 | NULL
1393553097 | 14.2 | 23.3
1412857868 | 16.0 | 14.2
1412857965 | 201.1 | 16.0
........
MySQL版本:5.7.24:
mysql> select version();
+-------------------------+
| version() |
+-------------------------+
| 5.7.24-0ubuntu0.16.04.1 |
+-------------------------+
答案 0 :(得分:1)
尝试一下:
SELECT time_stamp,
price,
(SELECT e2.price
FROM example e2
WHERE e2.time_stamp < e1.time_stamp
ORDER BY e2.time_stamp DESC
LIMIT 1
) AS prev_price
FROM example e1
ORDER BY e1.time_stamp ASC