Join GitHub today
hi，I have some questions about subqueries,Thanks #94
The subqueries is
"select(c for c in Changes if (c.id,c.tag) in select( (d.id,max(d.tag)) for d in Changes if d.tag>=tag))"
It means to find the row which has the biggest tag with "group by Changes.id" .
I run the program,PonyOrm convert it to SQL like this:
SELECT `c`.`a_id`, `c`.`id`, `c`.`relation_path`, `c`.`time`, `c`.`tag`, `c`.`type` FROM `changes` `c` WHERE (`c`.`id`, `c`.`tag`) IN ( SELECT `d`.`id`, MAX(`d`.`tag`) FROM `changes` `d` WHERE `d`.`tag` >= %s AND MAX(`d`.`tag`) IS NOT NULL GROUP BY `d`.`id` )
Why does the SQL contain this part?
Thanks for anwser
Thanks for your report!
The error was caused by the bug and I have fixed it. You can get new code from GitHub and check if it works for you.
This part is necessary for subqueries with
SELECT t1.a FROM t1 WHERE t1.b NOT IN (SELECT t2.c FROM t2)
Because of this, Pony adds additional check to the inner query:
SELECT t1.a FROM t1 WHERE t1.b NOT IN (SELECT t2.c FROM t2 WHERE t2.c IS NOT NULL)
This way the query works as expected. But It turns out that Pony had two bugs here:
Now both of this bugs are fixed, and your query should work. But I'm not sure that the query does what you expect. Because of this I want to clarify how aggregation works in this case. Consider this query which uses our standard example database with students and courses:
>>> from pony.orm.examples.presentation import * >>> select((s.group, max(s.gpa)) for s in Student)[:]
SELECT "s"."group", MAX("s"."gpa") FROM "Student" "s" GROUP BY "s"."group"
As you can see, this query adds
>>> select((s.id, max(s.gpa)) for s in Student)[:]
SELECT "s"."id", MAX("s"."gpa") FROM "Student" "s" GROUP BY "s"."id"
In this query, we use
select((s.id, s.gpa) for s in Student)[:]
So, when we perform grouping, we need to group rows by the column which has duplicate values, like
From my point of view, the
I don't know what is the correct query in your case, because I don't quite understand the intention of your query. But the next two queries may give you some hints:
Hope this helps. Thanks again for the bug reporting.