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
解释查询:MySQL查询速度很慢,需要帮助优化
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的具有约十亿行,表2是具有20K行查找表,为了555约为100万行。 id2约占整个表格1的10%。 table2基本上是具有所有id1的查找表。 id1-> orderid有多对一的关系。换句话说,一个id1只属于一个orderid。 除userid外,table2和table1不具有空值。
我想计算每个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做了左连接第一或where语句第一?应存储顺序555到不同的表,然后运行他们查询?
fields'table1.id2','table2.orderid' have index? – 2014-10-03 19:23:54
将“EXPLAIN”放在您的查询之前并执行它.MySQL将吐出执行路径和优化你的查询,你可以在加入之前看到它是否先过滤“555”(我非常怀疑它的确如此)。http://dev.mysql.com/doc/refman/5.0/en/explain。 html – JNevill 2014-10-03 19:25:10
[阅读关于'EXPLAIN'](http://dev.mysql.com/doc/refman/5.0/en/using-explain.html)。 – Air 2014-10-03 19:25:15