重构查询没有子查询但加入?

时间:2016-08-15 15:49:53

标签: sql postgresql join amazon-redshift

我试图在不使用子查询的情况下重写以下查询,因为我无法负担散列连接。

SELECT 
  COUNT(wins.bid) as wins, 
  to_char((TIMESTAMP 'epoch' + bidRequestTime * INTERVAL '1 Second'), 'DD') as date,
  COUNT(impression.bid) as impression, 
  lid, 
  COUNT(b.bid) as requests, 
  ROUND(SUM(spendCalc),2) as spend 
FROM (
  SELECT lid, bids.bid,bidRequestTime,price::float*COUNT(impression.bid)/1000::float/.80::float as spendCalc
  FROM bids
  LEFT OUTER JOIN wins on wins.bid = bids.bid
  LEFT OUTER JOIN impressions impression ON impression.bid = bids.bid
  WHERE bidRequestTime BETWEEN 1470614400 AND 1471219200 
  GROUP BY price, bids.bid, bidRequestTime, lid
) b
LEFT OUTER JOIN wins on wins.bid = b.bid
LEFT OUTER JOIN impressions impression ON impression.bid = b.bid
WHERE bidRequestTime BETWEEN 1470614400 AND 1471219200  
GROUP BY lid, date 

有什么建议吗?在此先感谢。

1 个答案:

答案 0 :(得分:0)

很难确切地说出你的问题是什么...但是这里有一些技巧删除外连接并使用CTE来减少搜索空间....可能会或可能不会工作,需要查看有关您的更多详细信息模型可以肯定。

WITH mybid as
(
  SELECT bid, bidRequestTime
  FROM bids 
  WHERE bidRequestTime BETWEEN 1470614400 AND 1471219200  
)
SELECT 
  COUNT(wins_bid) as wins, 
  to_char((TIMESTAMP 'epoch' + bidRequestTime * INTERVAL '1 Second'), 'DD') as date,
  COUNT(imp_bid) as impression, 
  lid, 
  COUNT(b.bid) as requests, 
  ROUND(SUM(spendCalc),2) as spend 
FROM (
  SELECT wins.bid as wins_bid, lid, bids.bid, bidRequestTime, impression.bid as imp_bid,  price::float*COUNT(impression.bid)/1000::float/.80::float as spendCalc
  FROM mybid as bids
  LEFT OUTER JOIN wins on wins.bid = bids.bid
  LEFT OUTER JOIN impressions impression ON impression.bid = bids.bid
  GROUP BY price, bids.bid, bidRequestTime, lid
) b
GROUP BY lid, date