有一个表table1,里面用到的主要两个字段如下
times datetime
length int 现在表中有几万条记录,需要查询times时间相隔在30秒,并且前一条记录的length< 100 的记录。
我先creat table t1 as select * from table1 where length<100然后两个表再根据时间比,这样过了很久也得不到结果。有谁有什么更好的方法吗
times datetime
length int 现在表中有几万条记录,需要查询times时间相隔在30秒,并且前一条记录的length< 100 的记录。
我先creat table t1 as select * from table1 where length<100然后两个表再根据时间比,这样过了很久也得不到结果。有谁有什么更好的方法吗
ALTER TABLE table1 ADD INDEX (calling_num);
ALTER TABLE table1 ADD INDEX (called_num);
ALTER TABLE table1 ADD INDEX (talk_len);
ALTER TABLE table2 ADD INDEX (begin_time);
ALTER TABLE table2 ADD INDEX (calling_num);
ALTER TABLE table2 ADD INDEX (called_num);
ALTER TABLE table2 ADD INDEX (talk_len);select from table1 ,table2 where (table1.calling=table2.calling or table1.called=table2.called) and (table1.time<table2.time) and TIMESTAMPDIFF(SECOND,table1.time,table2.time)<20;
2)没有适合的索引,你创建的索引全是单个字段的索引。
3)使用了TIMESTAMPDIFF(SECOND,table1.time,table2.time)<20这种通过函数来计算后判断,无法利用索引。给出你的 explain select from table1 ,table2 where (table1.calling=table2.calling or table1.called=table2.called) and (table1.time<table2.time) and TIMESTAMPDIFF(SECOND,table1.time,table2.time)<20;
和 show index from table1;
show index from table2;
以供分析。
1)粘贴的时候去空格把*丢了,这个是我的失误
2)何谓合适的索引,没太懂,请教下,或者哪有资料我学习学习
3)计算时间差的话还有什么更好的方法吗?explain 的结果
id select_type table type possible_keys Extra
1 SIMPLE table1 ALL time,calling,called
1 SIMPLE table2 ALL calling,called Range checked for each record (index map: 0x6)show index 的 结果(2个表的结果基本一样)
table Non_unique Key_name Seq_in_indx Column_name Colation Cardinality
table1 1 begin_time 1 begin_time A 7360
table1 1 calling_num 1 calling_num A 58884
table1 1 called_num 1 called_num A 58884
explain 剩下4列 key, key_len ,ref 是空的,rows列一个是58884,一个是91709table1 1 time 1 begin_time A 7360 YES BTREE
table1 1 calling 1 calling_num A 58884 YES BTREE
table1 1 called 1 called_num A 58884 YES BTREE table2 1 time 1 begin_time A 7642 YES BTREE
table2 1 calling 1 calling_num A 91709 YES BTREE
table2 1 called 1 called_num A 91709 YES BTREE 根据结果看索引根本就没有用,这就是我不明白的地方