Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#30203 closed Bug (duplicate)

Union with group by don't generate correct Subquery

Reported by: Nikolas Owned by: nobody
Component: Database layer (models, ORM) Version: 1.11
Severity: Normal Keywords: union, group by
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Nikolas)

Simplified for example:
have simple query

    qs1: QuerySet = User.objects.filter(id__gt=10)

    qs1 = qs1.values('is_active').annotate(id=Count('pk'))

generate:

SELECT "suser_customuser"."is_active",
       COUNT("suser_customuser"."id") AS "id"
FROM "suser_customuser"
WHERE "suser_customuser"."id" > 10
GROUP BY "suser_customuser"."is_active"

all correct, now i wont use union

    qs1: QuerySet = User.objects.filter(id__gt=10)
    qs2: QuerySet = User.objects.filter(id__lt=10)

    qs1 = qs1.values('is_active').annotate(id=Count('pk'))

now get not correct SQL:

  (SELECT "suser_customuser"."is_active",
          "suser_customuser"."id"
   FROM "suser_customuser"
   WHERE "suser_customuser"."id" > 10)
UNION
  (SELECT "suser_customuser"."is_active",
          "suser_customuser"."id"
   FROM "suser_customuser"
   WHERE "suser_customuser"."id" < 10)

expected:

select *
from
  ((SELECT "suser_customuser"."is_active",
          "suser_customuser"."id"
   FROM "suser_customuser"
   WHERE "suser_customuser"."id" > 10)
UNION
  (SELECT "suser_customuser"."is_active",
          "suser_customuser"."id"
   FROM "suser_customuser"
   WHERE "suser_customuser"."id" < 10)) U0
group by is_active, id

i think this is bug, if not why not show any warning or exception?
or just say how rewrite query for correct use Subquery

Change History (3)

comment:1 by Simon Charette, 5 years ago

Resolution: needsinfo
Status: newclosed

Hello there, I don't think union support aggregation yet but this is hard to tell without the exact model definitions and queries used to replicate the issue.

Please re-open this ticket if you can provide a slimmed down version of your models and querysets that reproduce the issue as right now it's not clear if/how Django is at fault.

comment:2 by Nikolas, 5 years ago

Description: modified (diff)

comment:3 by Tim Graham, 5 years ago

Resolution: needsinfoduplicate

Duplicate ticket created at #30209 with more details. (Next time, please reopen the ticket rather than creating a duplicate.)

Note: See TracTickets for help on using tickets.
Back to Top