问题描述
我是MysqL的新手,我想要一些帮助来设置MySQL查询以特定输出格式从几张表(约100,000行)中提取一些数据。
此问题涉及三个sql表:
allusers
:此包含用户信息。感兴趣的列是userid
和vip
table1
和table2
包含数据,但它们也有一个userid
列,该列与userid
中的allusers
列匹配。
我想做什么:
我想创建一个查询,该查询通过allusers
搜索,找到VIP中的userid
,然后计算table1
和{由table2
分组的{1}}。所以,我想要的输出是:
userid
我到目前为止所做的:
我创建了以下语句:
userid | Count in Table1 | Count in Table2
1 | 5 | 21
5 | 16 | 31
8 | 21 | 12
这使我接近想要的东西。但是现在,我想添加另一列,其中分别包含SELECT userid,count(1)
FROM table1
WHERE userid IN (SELECT userid FROM allusers WHERE vip IS NOT NULL)
GROUP BY userid
我也尝试过使用这样的联接:
table2
但是,此查询花费了很长时间,因此我不得不取消该查询。我认为这是因为对如此大的表使用联接非常低效。
类似问题
This one sums up the counts across tables,while I need the counts separated into columns
谢谢!
解决方法
您需要先进行预聚合,然后再加入,否则如果用户在table1
和table2
中都有几行,结果将不会是您期望的。此外,在您这样的情况下,预聚合通常比外部聚合更有效。
考虑:
select a.userid,t1.cnt cnt1,t2.cnt cnt2
from allusers a
left join (select userid,count(*) cnt from table1 group by userid) t1
on t1.userid = a.userid
left join (select userid,count(*) cnt from table2 group by userid) t2
on t2.userid = a.userid
where a.vip is not null
,
在这种情况下,我会建议相关子查询:
select a.userid,(select count(*) from table1 t1 where t1.userid = a.userid) as cnt1,(select count(*) from table2 t2 where t2.userid = a.userid) as cnt2
from allusers a
where a.vip is not null;
我之所以推荐这种方法,是因为您正在过滤alllusers
表。这意味着预聚合方法可能正在做其他不必要的工作。