gpt4 book ai didi

mysql查询速度慢,需要帮助优化

转载 作者:太空宇宙 更新时间:2023-11-03 12:06:39 26 4
gpt4 key购买 nike

table1

time userid id1 id2
9/1/2014 3:30 user1 123 555
9/1/2014 3:32 user1 123 555
9/1/2014 3:13 user1 123 555
9/1/2014 3:15 user1 123 555
9/1/2014 3:38 user2 321 555
9/1/2014 3:21 user2 321 555
9/1/2014 3:38 user2 456 666
9/1/2014 3:21 user2 456 666

table2

id1 orderid
321 order1
123 order2

解释查询:

select_type table   type possible index  key         key_len    ref        row     Extra
SIMPLE table1 ALL 934420 Using where; Using temporary; Using filesort
SIMPLE table2 ref lookupindex lookupindex 33 table1.id1 1

我的 table1 有大约 10 亿行,table2 是有 20k 行的查找表,order 555 大约有 1 亿行。id2 大约占 table1 总数的 10%。 table2 基本上是具有所有 id1 的查找表。 id1-> orderid 具有多对一关系。也就是说一个id1只属于一个orderid。table2 和 table1 除 userid 外没有空值。

我想为每个 orderid 计算唯一用户。

我的查询需要很长时间才能运行(没有在 5 小时内完成,所以我停止了它),我不确定除了索引之外如何优化它。我在 table2.id1 上有索引。

select  table2.orderid, count(distinct userid)
from table1 left join table2 on table1.id1 = table2.id1
where table1.id2="555"
group by table2.orderid

mysql是先做left join还是先做where statement?应该把555这个order存到不同的表再运行他们查询?

最佳答案

问题是你的 distinct 操作,那个操作非常昂贵。您可以通过在 userid 上放置索引来提高效率,这两个键也应该有一个索引。我不确定您要在功能上尝试做什么,但也许其他方法也可以作为替代方案。

关于mysql查询速度慢,需要帮助优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26185423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com