Ticket #1254 (closed defect: fixed)
IN-Subquery with LIMIT and 1:n relation generates incorrect SQL
| Reported by: | Tanken | Owned by: | romanb |
|---|---|---|---|
| Priority: | major | Milestone: | 1.0.3 |
| Component: | Query/Hydration | Version: | 1.0.0 |
| Severity: | Keywords: | ||
| Cc: | Has Test: | no | |
| Status: | Pending Core Response | Has Patch: | no |
Description (last modified by Tanken) (diff)
I'm doing a somewhat complicated, but not unusual query for the most recent record of a relation (A) grouped by a certain category within this relation. One way to achieve this (according to http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html), is by doing a subquery for the maximum in the category group:
SELECT cat, name, created_at
FROM A a1
WHERE created_at IN (SELECT MAX(a2.created_at)
FROM A a2
WHERE a1.cat = a2.cat);
This seems to work, but then I had to join another relation (B) on A and also apply a LIMIT to the outer query, as I needed to paginate. So the query should look like this:
SELECT cat, name, created_at
FROM A a1
LEFT
JOIN B b1 ON a1.id = b.a_id
WHERE created_at IN (SELECT MAX(a2.created_at)
FROM A a2
WHERE a1.cat = a2.cat)
LIMIT 10;
But this combination results in a subquery which uses the wrong aliases, like this:
SELECT cat, name, created_at
FROM A a1
LEFT
JOIN B b1 ON a1.id = b.a_id
WHERE created_at IN (SELECT MAX(a1.created_at)
FROM A a1
WHERE a1.cat = a1.cat)
LIMIT 10;
without the limit it appears to work and without the join, too.
test case committed: http://trac.phpdoctrine.org/browser/branches/0.11/tests/Ticket/1254TestCase.php