【问题标题】:Selecting Counts from Different Tables with a Subquery使用子查询从不同表中选择计数
【发布时间】:2020-09-03 15:10:11
【问题描述】:

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

本题涉及三个SQL表:

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

table1table2 包含数据,但它们也有一个 userid 列,与 allusers 中的 userid 列匹配。

我想做的事:

我想创建一个查询,它搜索allusers,找到VIP 的userid,然后计算table1table2 中的记录数,按@ 分组987654335@。所以,我想要的输出是:

  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

我也尝试过使用这样的连接:

select A.userid, count(T1.userid), count(T2.userid) from allusers A
left join table1 T1 on T1.userid = A.userid
left join table2 T2 on T2.userid = A.userid
where A.vip is not null
group by A.userid

但是,这个查询花费了很长时间,我不得不终止查询。我假设这是因为对如此大的表使用联接效率非常低。

类似问题

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

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

谢谢!

【问题讨论】:

    标签: mysql sql group-by count left-join


    【解决方案1】:

    您需要先预聚合,然后加入,否则如果用户在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
    

    【讨论】:

    • 我从来没有考虑过预先聚合。但这更有意义。这个查询完美地工作。谢谢。
    【解决方案2】:

    这是我推荐相关子查询的情况:

    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 表。这意味着预聚合方法可能会做额外的、不必要的工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2022-01-02
      • 1970-01-01
      • 2015-11-11
      相关资源
      最近更新 更多