﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
16018	Aggregation annotate(Max()) nonoptimal query.	fckin.spam@…	nobody	"I've asked this question in [https://groups.google.com/group/django-users/browse_thread/thread/615f23d359908b77?hl=ru django-users] and got advice to report.
Here is the point.

Model: 

{{{
class Home (models.Model): 
    person = models.ForeignKey (Person) 
    state = models.ForeignKey (States) 
    date = models.DateTimeField () 
    host = models.ForeignKey (Hosts) 
    time_spent = models.PositiveIntegerField (null = True)
}}}
 
Here is the expression with query it makes:

{{{
>>> print Home.objects.values('person').annotate(Max('id')).order_by().query

SELECT `main_home`.`person_id`, MAX(`main_home`.`id`) AS `id__max` 
FROM `main_home` 
GROUP BY `main_home`.`person_id`, `main_home`.`person_id` 
ORDER BY NULL
}}}

GROUP BY formed with double `main_home`.`person_id`. Let's see what happen in this case:

{{{
mysql> explain SELECT `main_home`.`person_id`, MAX(`main_home`.`id`)  AS `id__max`  FROM `main_home`  GROUP BY `main_home`.`person_id`, `main_home`.`person_id`  ORDER BY NULL;
+----+-------------+-----------+-------+---------------+--------------------+---------+------+------+------------------------------+
| id | select_type | table     | type  | possible_keys | key                | key_len | ref  | rows | Extra                        |
+----+-------------+-----------+-------+---------------+--------------------+---------+------+------+------------------------------+
|  1 | SIMPLE      | main_home | index | NULL          | main_home_21b911c5 | 4       | NULL | 4604 | Using index; Using temporary |
+----+-------------+-----------+-------+---------------+--------------------+---------+------+------+------------------------------+
}}}

In ""Extra"" you can see ""Using temporary"" option.
Expression execution takes really long time, despite table indexes.

If i'll manually remove `main_home`.`person_id` doubling from mysql query, ""Using temporary"" will disappear and execution runs a times fister."	Bug	closed	Database layer (models, ORM)	1.3	Normal	duplicate	annotate group_by group twice	evgenpioneer@…	Unreviewed	0	0	0	0	0	0
