Opened 14 years ago
Closed 14 years ago
#15709 closed Cleanup/optimization (fixed)
Duplicated group_by condition
Reported by: | ziangsong | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.3 |
Severity: | Normal | Keywords: | group_by, annotate |
Cc: | ziangsong | Triage Stage: | Ready for checkin |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
So I want to implement this SQL:
selelct id, count(*), max(insert_date) as m_d
from Book
group by id
Here is the Django ORM query:
q = Book.objects.values('id').annotate(c = Count('id'), m_d = Max('insert_date')).order_by()
However, the translated sql is like this:
selelct id, count(*), max(insert_date) as m_d
from Book
group by id, id <-here is another id! It messed up things!
Btw, the id in Book is a foreign key to another table and I am using MySql database.
Attachments (1)
Change History (10)
comment:1 by , 14 years ago
Cc: | added |
---|---|
Component: | Uncategorized → Database layer (models, ORM) |
milestone: | → 1.3 |
comment:2 by , 14 years ago
Triage Stage: | Unreviewed → Accepted |
---|
comment:3 by , 14 years ago
Has patch: | set |
---|---|
milestone: | 1.3 |
The attached patch fixes this problem (hopefully) by not letting group_by clause duplicates through. I don't think duplicated entries in GROUP BY ever make sense.
Test included.
by , 14 years ago
Attachment: | 15709.diff added |
---|
comment:5 by , 14 years ago
Could you promote this issue to "Ready for checkin" if it fixes the problem for you? Thanks!
comment:6 by , 14 years ago
Triage Stage: | Accepted → Ready for checkin |
---|
comment:7 by , 14 years ago
Type: | → Cleanup/optimization |
---|
comment:8 by , 14 years ago
Severity: | → Normal |
---|
Some quick testing shows that the issue even exists when the Count('id') is left away:
Inside django.db.models.sql.compiler.SQLCompiler.get_grouping, both group_by and self.query.select contain ('page_page', 'parent_id') which causes the duplicated GROUP BY clause.