工作中会经常写SQL,而且工作中查询的数据量,一般都是几百万,甚至几亿的数据量。如果自己的SQL写的很烂,就可能导致查询了很久也不会跑出结果来。而我在工作中写SQL经常遇见的一个问题就是一对多关联导致数据发散。因此,这篇文章,主要记录一对多关联导致数据发散的应对方案。
多表关联优化的例子
我之前写了一个SQL,运行了一个多小时,也没有运行出来。
下面我列出这个SQL的逻辑:
SELECT t1.active_date,
t1.platform_name,
t1.type,
COUNT(DISTINCT t1.uid) AS user_cnt1,
count(DISTINCT case when t2.uid is not null then t2.uid end) as user_cnt2,
count(DISTINCT case when t3.uid is not null then t3.uid end) as user_cnt3
FROM table1 as t1