使用union all语句时如何避免多次连接?

时间:2017-10-20 22:34:40

标签: postgresql

我正在进行一个查询,我点了一句话:

SELECT tpd.timestamp::Date,'Mon' AS Label,
       count(tpd.aggregated)
FROM tap.deving AS tpd INNER JOIN
  (select DATE_TRUNC('week', timestamp),  MAX(timestamp) AS max_timestamp
   from tap.deving
   group by DATE_TRUNC('week', timestamp)
  ) b
on tpd.timestamp = b.max_timestamp 
left JOIN ca.hardware AS ch ON tpd.dev = ch.name
left JOIN ca.sites AS css ON css.id = ch.id
WHERE (tpd.aggregated=TRUE)
  AND (css.country='USA') and (tpd.timestamp::date=now()::Date - interval '1 day') group by tpd.timestamp
UNION ALL
SELECT tpd.timestamp::date,'Tap but not' AS Label,
       count(tpd.tap)
FROM tap.deving AS tpd INNER JOIN
  (select DATE_TRUNC('week', timestamp),  MAX(timestamp) AS max_timestamp
   from tap.deving
   group by DATE_TRUNC('week', timestamp)
  ) b
on tpd.timestamp = b.max_timestamp 
left JOIN ca.hardware AS ch ON tpd.dev = ch.name
left JOIN ca.sites AS css ON css.id = ch.id
WHERE (tpd.tap=true)
  AND (tpd.aggregated=false) and (tpd.needs_to_be=true)
  AND (css.country='USA')  and (tpd.timestamp::date=now()::Date - interval '1 day') group by tpd.timestamp

我在许多SO帖子的帮助下写了这个查询,它已经变得非常混乱和超级慢。我无法理解如何优化此查询。

1 个答案:

答案 0 :(得分:1)

你可以试试这个查询。

 SELECT tpd.timestamp::Date,CASE tpd.aggregated
      WHEN false THEN 'Tap but not'
      WHEN true THEN 'Mon' as Label,
       count(tpd.aggregated)
FROM tap.deving AS tpd INNER JOIN
  (select DATE_TRUNC('week', timestamp),  MAX(timestamp) AS max_timestamp
   from tap.deving
   group by DATE_TRUNC('week', timestamp)
  ) b
on tpd.timestamp = b.max_timestamp 
left JOIN ca.hardware AS ch ON tpd.dev = ch.name
left JOIN ca.sites AS css ON css.id = ch.id
WHERE ((tpd.aggregated=TRUE)  or ((tpd.tap=true)  AND (tpd.aggregated=false) and (tpd.needs_to_be=true)))
  AND (css.country='USA') and (tpd.timestamp::date=now()::Date - interval '1 day') group by tpd.timestamp;