This below query works as expected:
SELECT
reports.*
FROM
reports
INNER JOIN
units
ON units.id = reports.unit_id
WHERE
reports.unit_id IN (1111, 1112, 1113)
AND
(
reports.id =
(
SELECT reports.id
FROM reports
WHERE reports.unit_id = units.id
ORDER BY time desc
LIMIT 1
)
)
It returns the last 3 reports associated with the given units by time. How come that SELECT subquery returns 3 ids rather than just 1 even though we specifiy LIMIT 1? This is what I wanted. I'm just curious how it works.
FROM ... WHEREclauses (which are 3 here.) – ypercubeᵀᴹ Mar 06 '14 at 00:20FROMclause, even after restricting with the first condition in theWHEREmay be more than 3. But the distinctunit.idvalues in those rows are 3 and these values are used inside the correlated subquery. Whether the DBMS runs the subquery 3 or a million times depends on the implemenation (read optimizer.) – ypercubeᵀᴹ Mar 06 '14 at 00:26