Monday, October 27, 2014

Re: Slow SQL query

> Den 27/10/2014 kl. 13.20 skrev Collin Anderson <cmawebsite@gmail.com>:
>
> mysql> explain SELECT COUNT(*)
> -> FROM `order_order`
> -> WHERE `order_order`.`status` != 4
> -> AND (`order_order`.`user_id` = 12345 OR `order_order`.`account_number`
> -> = 123456);
> +----+-------------+-------------+------+-------------------------------------------------------------------------------------+------+---------+------+--------+-------------+
> | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
> +----+-------------+-------------+------+-------------------------------------------------------------------------------------+------+---------+------+--------+-------------+
> | 1 | SIMPLE | order_order | ALL | order_order_fbfc09f1,order_order_979d4f1e,order_order_48fb58bb,order_order_309e75c7 | NULL | NULL | NULL | 338275 | Using where |
> +----+-------------+-------------+------+-------------------------------------------------------------------------------------+------+---------+------+--------+-------------+
> 1 row in set (0.16 sec)
>
> I can't get it to use the indexes when I have the "status" clause.

Note that your indexes are on individual columns, not combined. So MySQL has to choose one of the indexes; it can't combine them. It's probably choosing the state index, then deciding that the cardinality is very low (or stats show that state=4 is true for more than n pct of the rows) and then does a full table scan.

You might benefit from adding combined indexes with status and account_number|user.

class Meta:
index_together = [
['status', 'account_number'],
['status', 'user'],
]


Erik

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1B735AD7-8D31-4EE5-AB10-9B15AC443CE5%40cederstrand.dk.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment