【问题标题】:MySQL multi-step GROUP BY without subqueryMySQL 多步 GROUP BY 没有子查询
【发布时间】:2014-12-11 23:03:17
【问题描述】:

我正在努力改进我继承的一些查询,并且很好奇是否可以执行以下操作 - 给定一个看起来像这样的表 the_table

  id   uri
  ---+-------------------------
   1   /foo/bar/x
   1   /foo/bar/y
   1   /foo/boo
   2   /alpha/beta/carotine
   2   /alpha/delic/ipa
   3   /plastik/man/spastik
   3   /plastik/man/krakpot
   3   /plastik/man/helikopter

作为一个隐含的中间步骤,我想将这些按uri 的第一个 + 2 个元组分组。该步骤的结果如下所示:

  id   base           
  ---+---------------
   1   /foo/bar      
   1   /foo/boo      
   2   /alpha/beta   
   2   /alpha/delic  
   3   /plastik/man

最终结果将反映每个唯一 id 的唯一 tuple1 + tuple2 值的数量:

  id   cnt
  ---+-----
   1   2
   2   2
   3   1

我可以实现这些结果,但不能不进行子查询(以获取上述隐式步骤的结果),然后从中选择/分组。比如:

SELECT
  id,
  count(base) cnt
FROM (
  SELECT
    id,
    substring_index(uri, '/', 3) AS base
  FROM the_table
  GROUP BY id, base
)
GROUP BY id;

我想要避免子查询的原因是我正在处理一个相当大的(20M 行)数据集,并且子查询变得非常昂贵。直觉告诉我这是不可行的,但我想我会问...

【问题讨论】:

    标签: mysql select group-by


    【解决方案1】:

    不需要子查询——您可以使用countdistinct 来获得相同的结果:

    SELECT
        id,
        count(distinct substring_index(uri, '/', 3)) AS base
    FROM the_table
    GROUP BY id
    

    顺便说一句——这将返回 1 的 id 3 计数——我认为这是您发帖中的拼写错误。

    【讨论】:

    • 稍后我会仔细看看这里,谢谢。是的,您对我问题中的错字是正确的。固定。
    • 这太简单了,我不敢相信我没有尝试过。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多