获得Postgresql查询的性能

时间:2016-06-21 12:03:17

标签: sql postgresql azure ubuntu

我有一个带有非规范化模式的postgresql数据库(1表),大约有4百万条目。现在我有了这个问题:

SELECT
  count(*) AS Total,
  (SELECT count(*) FROM table
   WHERE "Timestamp" > current_timestamp - INTERVAL '1 hour' AND "tableName" LIKE '%ping%') AS hour,

  (SELECT count(*) FROM table
   WHERE "Timestamp" > now() :: DATE AND "tableName" LIKE '%ping%') AS day,

  (SELECT count(*)
   FROM table
   WHERE "Timestamp" > now() :: DATE - INTERVAL '1 day' AND
         "Timestamp" <= now() :: DATE - INTERVAL '1 day' AND "tableName" LIKE '%ping%') AS yesterday,

  (SELECT count(*) FROM table
   WHERE "Timestamp" > now() :: DATE - INTERVAL '2 day' AND
         "Timestamp" <= now() :: DATE - INTERVAL '1 day' AND "tableName" LIKE '%ping%') AS "dayBeforeYesterday",

  (SELECT count(*)
   FROM table WHERE "Timestamp" > current_timestamp - INTERVAL '1 week' AND "tableName" LIKE '%ping%') AS week,

  (SELECT count(*)
   FROM table
   WHERE "Timetamp" > current_timestamp - INTERVAL '2 week' AND
        "Timestamp" < current_timestamp - INTERVAL '1 week' AND "tableName" LIKE '%ping%') AS "lastWeek",

  (SELECT count(*)
   FROM table
   WHERE "Timestamp" > current_timestamp - INTERVAL '3 week' AND
        "Timestamp" < current_timestamp - INTERVAL '2 week' AND "tableName" LIKE '%ping%') AS "weekBeforeLastWeek",

  (SELECT count(*)
   FROM table
   WHERE"Timestamp" > current_timestamp - INTERVAL '1 month' AND "tableName" LIKE '%ping%')AS month

FROM table WHERE "tableName" LIKE '%ping%';

这需要大约14秒到2分钟(取决于其他事情的进展)。但我的服务器,这是一个在Azure上托管的ubuntu的虚拟机,总是有100%的CPU覆盖。 如果我检查postgesql的统计信息,它主要是这个查询,它会阻塞整个CPU。 它是具有2个核心,7GB SSD的D2 VM。 有没有办法在不升级Azure包的情况下加快速度?

1 个答案:

答案 0 :(得分:2)

使用case表达式来进行条件聚合,而不是所有这些子查询:

SELECT
  count(*) AS Total,
  count(case when "Timestamp" > current_timestamp - INTERVAL '1 hour' AND "tableName" LIKE '%ping%' then 1 end) AS hour,
...