我有這樣的SQL:如何優化這個SQL在MySQL
select t1.id,t1.type from collect t1
where t1.type='1' and t1.status='1'
and t1.total>(t1.totalComplate+t1.totalIng)
and id not in(
select tid from collect_log t2
where t2.tid=t1.id and t2.bid='1146')
limit 1;
是是好的,但如果我用一個指示命令其表現似乎不太好和:
select t1.id,t1.type from collect t1
where t1.type='1' and t1.status='1'
and t1.total>(t1.totalComplate+t1.totalIng)
and id not in(
select tid from collect_log t2
where t2.tid=t1.id and t2.bid='1146')
order by t1.id asc
limit 1;
它變得更糟。 我如何優化這個?
這裏解釋一下:
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-------+------+---------------+-----+---------+-----------------+------+-----------------------------+
| 1 | PRIMARY | t1 | ref | i2,i1,i3 | i1 | 4 | const,const | 99 | Using where; Using filesort |
| 2 | DEPENDENT SUBQUERY | t2 | ref | i5 | i5 | 65 | img.t1.id,const | 2 | Using where; Using index
這是因爲數學正在做的很慢。你有沒有試過把'和t1.total>(t1.totalComplate + t1.totalIng)'放在'limit'的最前面,以減小操作執行結果集的大小? – AgmLauncher
你定義了哪些索引? – eggyal
沒有Agmlauncher,我沒有試過,怎麼樣? –