使用子查询从不同的表中选择计数

问题描述

我是MysqL的新手,我想要一些帮助来设置MySQL查询以特定输出格式从几张表(约100,000行)中提取一些数据。

此问题涉及三个sql表:

allusers:此包含用户信息。感兴趣的列是useridvip

table1table2包含数据,但它们也有一个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 is looking for a similar result as I am,but doesn't need nearly as much filtering with subqueries

This one sums up the counts across tables,while I need the counts separated into columns

有人可以帮助我设置查询生成所需的数据吗?

谢谢!

解决方法

您需要先进行预聚合,然后再加入,否则如果用户在table1table2中都有几行,结果将不会是您期望的。此外,在您这样的情况下,预聚合通常比外部聚合更有效。

考虑:

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表。这意味着预聚合方法可能正在做其他不必要的工作。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...