如何在PostgreSQL中使用WITH编写子查询

时间:2019-03-06 04:11:32

标签: common-table-expression postgresql-9.4

我正在尝试使用以下命令获取narendramodi的Twitter数据。

SELECT b.t_id,a.profile_image,b.tweet_text,e.media_media_url,b.retweet_count,b.favorite_count as like_count,count(reply_to_status_id) as reply_count,f.tweet_impression_count,f.tweet_engagement_count,f.tweet_engagement_rate 
FROM twitter_users a LEFT JOIN twitter_tweets b on a.user_id=b.user_id 
LEFT JOIN twitter_tweet_replies c on b.t_id = c.t_id 
LEFT JOIN twitter_tweet_media e on b.t_id = e.t_id 
LEFT JOIN twitter_tweet_metric_aggregates f on f.metric_timestamp= 
(select max(metric_timestamp) FROM twitter_tweet_metric_aggregates g 
WHERE g.t_id=f.t_id and g.t_id=b.t_id) 
WHERE a.twitter_screen_name= 'narendramodi' 
GROUP BY  b.t_id,a.profile_image 
,b.tweet_text,b.retweet_count,b.favorite_count,
e.media_media_url,f.imp_count,f.eng_count,f.eng_rate);

查询工作正常,但是,在上面的查询中,我使用了子选择以基于时间戳获取imp_counts的最新数据。由于Query_cost很大,因此执行查询要花费15分钟以上。我想减少这种情况,应该能够在10秒内执行。因此,我试图使用WITH(CTE)表达式。

在这里

WITH metric_counts AS (
SELECT max(metric_timestamp),f.t_id 
FROM twitter_tweet_metric_aggregates f LEFT JOIN twitter_tweets b on 
f.t_id=b.t_id 
)
SELECT 
b.t_id,a.profile_image,b.tweet_text,e.media_media_url,b.retweet_count
,b.favorite_count as like_count, count(reply_to_status_id) as 
reply_count,metric_counts.imp_count
,metric_counts.eng_count,metric_counts.eng_rate 

FROM twitter_users as a 
LEFT JOIN twitter_tweets as b on a.twitter_user_id=b.twitter_user_id 
LEFT JOIN twitter_tweet_replies c on b.t_id = c.t_id 
LEFT JOIN twitter_tweet_media e on b.t_id = e.t_id 
LEFT JOIN metric_counts on metric_counts.t_id = b.t_id WHERE 
lower(a.twitter_screen_name)=lower('narendramodi') 
GROUP BY b.t_id,a.profile_image,b.tweet_text,e.media_media_url,
b.retweet_count,b.favorite_count, 
metric_counts.imp_count,metric_counts.eng_count,
metric_counts.eng_rate;

该查询正在执行,但未提供该特定表中的imp_count,eng_count,eng_rate值。

注意:如果我删除该次选择查询,则该查询将在10秒内执行。但是,我希望也将其包括在内。为此,我使用了WITH但失败了。所以任何人都可以帮助我了解如何使用WITH表达式编写第一个查询。

0 个答案:

没有答案
相关问题