没有子查询但加入的重组查询?
Posted
技术标签:
【中文标题】没有子查询但加入的重组查询?【英文标题】:Restructure query without sub-query but join? 【发布时间】:2016-08-15 15:49:52 【问题描述】:我试图在不使用子查询的情况下重写以下查询,因为我负担不起哈希联接。
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
有什么建议吗?提前致谢。
【问题讨论】:
您能否对上面的查询进行一些格式化以使其更具可读性? 当你说你买不起哈希连接时,我不明白你的意思......到底是什么问题?这个查询慢吗? 是的,我有 20 亿条记录,子查询需要很多时间。我相信加入会花费更少的时间。 是的,如果您发布示例数据和所需的输出,那么在没有子查询的情况下进行查询并不是什么大问题。 获取子查询,将结果集插入临时表,索引临时表,然后将其与其余连接一起使用。 【参考方案1】:很难确切地说出您的问题是什么...但是这里有一些技巧可以删除外部连接并使用 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
【讨论】:
谢谢霍根!我正在尝试编写没有子查询的查询,只是加入。 @RedshiftGuy 这是不可能的,因为你正在做两个不同的分组。我不知道业务规则,所以我无法验证您是否可以通过一组来完成,但这应该没关系,因为我在这里取出了所有外部连接。以上是关于没有子查询但加入的重组查询?的主要内容,如果未能解决你的问题,请参考以下文章