mysql – List last logged users (GROUP BY AND ORDER BY)

Question:

I have two tables ( user and log ), and I would like to list users sorting by the last logged. I'm using GROUP BY to gather logs (since a user can own more than one).

The problem occurs when I add the ORDER BY , returning an error in the query:

Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'insidetv.log.data' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

SQL:

SELECT nome, log.data FROM usuario JOIN log ON usuario.codigo = log.codigo_usuario GROUP BY usuario.codigo ORDER BY log.data

Answer:

To list the last ones (descending), just add the clause ORDER BY DESC , where:

DESC: Descending
ASC: Ascendant

By default, the SQL language uses ASC (ascending/ascending form).

SQL:

SELECT nome, max(log.data) as last_data FROM usuario JOIN log ON usuario.codigo = log.codigo_usuario GROUP BY usuario.codigo ORDER BY last_data DESC
Scroll to Top