MySQL无子查询多步分组方式
我正在努力改进我继承的一些查询,我很好奇是否有可能执行以下操作-给定一个表MySQL无子查询多步分组方式,mysql,select,group-by,Mysql,Select,Group By,我正在努力改进我继承的一些查询,我很好奇是否有可能执行以下操作-给定一个表u表,如下所示: 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
u表,如下所示:
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
的第1+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;
我想避免使用子查询的原因是,我使用的是一个相当大(2000万行)的数据集,子查询的成本非常高。Gut告诉我这是不可行的,但我想我会这样问…不需要子查询——您可以使用count
和distinct
来获得相同的结果:
SELECT
id,
count(distinct substring_index(uri, '/', 3)) AS base
FROM the_table
GROUP BY id
顺便说一句——对于id 3,返回的计数为1——我想这是您的帖子中的一个输入错误。我稍后会仔细看一下,谢谢。是的,关于我问题中的打字错误,你是对的。修正了。这太简单了,我不敢相信我没有试过。谢谢