加快"找到或创建"从id和时间戳搜索的postgres查询

时间:2017-08-18 01:21:03

标签: sql c postgresql

我有一个postgres查询,我正在使用"查找或创建"但是,记录大约需要60-80毫秒才能完成~20k行,并且它是循环的一部分。运行整个循环开始拖出,目前在~20s,并且只会变得更长(整个循环在事务中)。我使用market_id和时间戳来选择行。

我怀疑这是给我带来麻烦的时间戳字段,但我不确定。我在C中使用。

以下是我创建表格的方法:

CREATE TABLE market_summary(
  id SERIAL PRIMARY KEY,
  market_id INT,
  market_name VARCHAR(20),
  high FLOAT,
  low FLOAT,
  volume FLOAT,
  last FLOAT,
  base_volume FLOAT,
  timestamp TIMESTAMP,
  bid FLOAT,
  ask FLOAT,
  open_buy_orders INT,
  open_sell_orders INT,
  previous_day FLOAT,
  market_creation_date TIMESTAMP,
  created_at TIMESTAMP default CURRENT_TIMESTAMP,
  updated_at TIMESTAMP default CURRENT_TIMESTAMP
)

以下是我使用的查询示例:

INSERT INTO market_summary(market_id,market_name,high,low,volume,last,base_volume,timestamp,bid,ask,open_buy_orders,open_sell_orders,previous_day,market_creation_date) 
SELECT 19, 'BTC-BITB', 0.000001, 0.000001, 37359913.914823, 0.000001, 21.940584, '2017-08-18T00:13:43.643', 0.000001, 0.000001, 310, 4255, 0.000001, '2015-02-15T23:07:32.777' 
  WHERE NOT EXISTS (
    SELECT (market_id,timestamp) FROM market_summary 
      WHERE market_id = 19 AND timestamp::timestamp = to_timestamp('2017-08-18T00:13:43.643', 'YYYY-MM-DDThh24:mi:ss.ms')
  );
SELECT * FROM market_summary 
    WHERE market_id = 19 AND timestamp::timestamp = to_timestamp('2017-08-18T00:13:43.643', 'YYYY-MM-DDThh24:mi:ss.ms');

最后是EXPLAIN ANALYZE:

    Insert on market_summary  (cost=19778.63..19778.69 rows=1 width=170)
->  Subquery Scan on "*SELECT*"  (cost=19778.63..19778.69 rows=1 width=170)
      ->  Result  (cost=19778.63..19778.64 rows=1 width=364)
            One-Time Filter: (NOT $0)
            InitPlan 1 (returns $0)
              ->  Seq Scan on market_summary market_summary_1  (cost=0.00..19778.63 rows=1 width=0)
                    Filter: ((market_id = 19) AND ("timestamp" = to_timestamp('2017-08-18T00:13:43.643'::text, 'YYYY-MM-DDThh24:mi:ss.ms'::text)))

有没有办法显着提高速度?

编辑: 我忘记了与市场的关系,市场有很多MarketSummary。

编辑2: 市场表:

CREATE TABLE markets(
  id SERIAL PRIMARY KEY,
  name VARCHAR(20),
  created_at TIMESTAMP default CURRENT_TIMESTAMP,
  updated_at TIMESTAMP default CURRENT_TIMESTAMP
)

0 个答案:

没有答案