I thought that selecting values from a subquery in SQL would only yield values from that subset until I found a very nasty bug in code. Here is an example of my problem.
I'm selecting the rows that contain the latest(max) function by date. This correctly returns 4 rows with the latest check in of each function.
select *, max(date) from cm where file_id == 5933 group by function_id;
file_id function_id date value max(date) 5933 64807 1407941297 1 1407941297 5933 64808 1407941297 11 1407941297 5933 895175 1306072348 1306072348 5933 895178 1363182349 1363182349
When selecting only the value from the subset above, it returns function values from previous dates, i.e. rows that don't belong in the subset above. You can see the result below where the dates are older than in the first subset.
select temp.function_id, temp.date, temp.value from (select *, max(date) from cm where file_id 5933 group by function_id) as temp;
function_id date value 64807 1306072348 1 <-outdated row, not in first subset 64808 1306072348 17 <-outdated row, not in first subset 895175 1306072348 895178 1363182349
What am I doing fundamentally wrong? Shouldn't selects performed on subqueries only return possible results from those subqueries?