SOSA SOSA - 1 year ago 85
SQL Question

SQL - Are columns always corresponding?

SELECT max(date) as lastdt,name,col1 FROM `consumption` group by name

In the above query, are values of
taken from the same row?

Answer Source

MySQL allows for non-aggregated columns to appear in the SELECT clause of a query. However the values of these columns are indeterminate.

If you want to get the col1 value that corresponds to the record having the maximum date value, then you will have to do an additional join:

FROM `consumption` AS t1
JOIN (SELECT max(`date`) as lastdt, name  
      FROM `consumption` 
      group by name) AS t2
ON = AND t1.`date` = t2.lastdt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download