Presto SQL中抽样用户过滤为何大幅改变查询结果?左连接后为何需IN过滤?
问题分析与解答
你的理解偏差出在左连接+t2.cluster_id IS NULL的过滤逻辑上,具体拆解:
- 先明确
t2的数据源:exploded_historical_users_clusters只包含sampled_users里的用户及其对应的cluster_id。 - 当
t3左连t2时,会出现两种满足t2.cluster_id IS NULL的情况:- 情况一:
t3.user_id属于sampled_users,但该用户在t3中的cluster_id不在自己的历史cluster列表里(即t2中没有匹配的记录) - 情况二:
t3.user_id根本不在sampled_users里,左连后t2的所有字段都是NULL,自然满足t2.cluster_id IS NULL
- 情况一:
所以你去掉AND t3.user_id IN (SELECT user_id FROM sampled_users)后,结果会包含大量不属于采样集的用户——这就是为什么结果里的user_id不来自sampled_users,同时调整采样阈值对结果大小没影响:因为非采样用户的数量远大于采样用户,采样比例的变化对整体结果的影响可以忽略。
这个过滤条件一点都不多余,它的核心作用是把情况二的非采样用户排除掉,只保留情况一中的采样用户。
如果想简化写法,可以把采样用户的过滤提前到JOIN阶段,逻辑更清晰:
WITH sampled_users AS ( SELECT a.user_id FROM table1 a JOIN table2 b ON a.user_id = b.user_id WHERE a.date='2024-05-29' AND b.date='2024-05-29' AND b.experiment = 'experiment_name' AND sampling_function(CAST(a.user_id AS VARCHAR)) <= 0.00001 AND b.condition = 'control' ), exploded_historical_users_clusters AS ( SELECT a.user_id, c.cluster_id FROM table1 a CROSS JOIN UNNEST(a.cluster_ids) AS c (cluster_id) JOIN sampled_users s ON a.user_id = s.user_id ) SELECT COUNT(DISTINCT t3.user_id) AS distinct_user_count, COUNT(*) AS total_rows FROM table3 t3 -- 先通过JOIN过滤出采样用户 JOIN sampled_users s ON t3.user_id = s.user_id LEFT JOIN exploded_historical_users_clusters t2 ON t3.user_id = t2.user_id AND t3.cluster_id = t2.cluster_id WHERE t3.date = '2024-05-29' AND t3.taxonomy = 'taxonomy_level_3' AND t3.version = 'version_1' AND t3.surface = 'surface_value' AND t3.count > 0 AND t2.cluster_id IS NULL;
内容的提问来源于stack exchange,提问作者elexhobby
相关产品推荐
相关产品推荐

