我有一个保存加密货币价格数据的数据库。价格数据请求如下所示:
SELECT timestamp, price FROM PRICES
WHERE timestamp > 1504703321
AND timestamp < 1504707321
AND exchange = (SELECT exid FROM EXCHANGES WHERE name = "exchange_name")
AND market = (SELECT mid FROM MARKETS WHERE name = "market_name")
AND side = (SELECT sid FROM SIDES WHERE name = "ASK")
AND id % 2 = 0
ORDER BY timestamp ASC";
应该很直接。为了简化这篇文章,我不会写下有关其他表格的更多信息。如果您需要更多信息,请随时提出,我会添加。
如你所见,我使用&#34;标准&#34;获取每一秒的mod方法(AND id % 2 = 0
)。但是,我遇到了一个问题:
用数据填充表的程序总是以相同的顺序添加新数据。假设我有两个交换,名为A
exid 1
和B
exid 2
。首先,添加A
行,然后添加B
行,然后再添加A
行,然后再添加B
,依此类推。
结果将是:
id exchange ...
1 1 ...
2 2 ...
3 1 ...
4 2 ...
对于每个id % 2
exchange = 1
,结果始终为!= 0
,表示上述查询的结果将为空。
如果可能的话,我只想通过修改SQL语句来解决这个问题,这意味着数据库/表和软件保持不变,并且尽可能地丢失性能。该表可以增长到400万行。
有没有办法实现这个目标?
答案 0 :(得分:2)
使用子查询并添加新列:
SELECT timestamp, price
FROM (SELECT p.timestamp, p.price, (@rn := @rn + 1) as rn
FROM PRICES p CROSS JOIN
(SELECT @rn := 0) params
WHERE timestamp > 1504703321 AND
timestamp < 1504707321 AND
exchange = (SELECT exid FROM EXCHANGES WHERE name = 'exchange_name') AND
market = (SELECT mid FROM MARKETS WHERE name = 'market_name') AND
side = (SELECT sid FROM SIDES WHERE name = 'ASK')
) p
WHERE rn % 2 = 0
ORDER BY timestamp ASC;