我有一张看起来像这样的桌子:
mysql> explain test_table;
+---------------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+-------------+------+-----+---------+-------+
| timestamp | datetime | NO | PRI | NULL | |
| id | varchar(64) | NO | PRI | NULL | |
| px_last | float | NO | | NULL | |
| twap | float | YES | | NULL | |
+---------------------+-------------+------+-----+---------+-------+
对于给定的符号和时间戳,我想将字段的值twap
向后移动一个时间步。
这张表:
mysql> select * from test_table;
+---------------------+-------+---------+-------+
| timestamp | id | px_last | twap |
+---------------------+-------+---------+-------+
| 2011-01-01 00:00:00 | apple | 101 | 101.1 |
| 2011-01-01 00:00:00 | pear | 50 | 50.1 |
| 2011-01-02 00:00:00 | apple | 102 | 112.8 |
| 2011-01-02 00:00:00 | pear | 51 | 57.3 |
| 2011-01-03 00:00:00 | pear | 52 | 59.1 |
| 2011-01-03 00:00:00 | apple | 103 | 104.1 |
+---------------------+-------+---------+-------+
最终应该是这样的:
mysql> select * from test_table;
+---------------------+-------+---------+-------+
| timestamp | id | px_last | twap |
+---------------------+-------+---------+-------+
| 2011-01-01 00:00:00 | apple | 101 | 112.8 |
| 2011-01-01 00:00:00 | pear | 50 | 57.3 |
| 2011-01-02 00:00:00 | apple | 102 | 104.1 |
| 2011-01-02 00:00:00 | pear | 51 | 59.1 |
| 2011-01-03 00:00:00 | pear | 52 | NULL |
| 2011-01-03 00:00:00 | apple | 103 | NULL |
+---------------------+-------+---------+-------+
我的第一种方法(使用这个例子:How to number rows...)是在每个符号中创建一个行号 (1, 2....n),然后将行号、符号和 twap 复制到一个临时表中,将临时表中每一行的行号减少1,然后将数据复制回原始表。
有没有办法在不创建临时表的情况下做到这一点?该表很大,超过 5000 万行并且还在增长,因此找到小于给定时间戳的最大时间戳效率不够高。