The query:
SELECT cus_id, total_due FROM invoice GROUP BY cus_id ORDER BY inv_id DESC
is invalid SQL because of the total_due
column in the SELECT
clause.
A query with GROUP BY
is allowed to contain in the SELECT
clause:
- expressions that are also present in the
GROUP BY
clause;
- expressions that use aggregate functions (aka "GROUP BY" functions);
- columns that are functionally dependent on columns that are present in the
GROUP BY
clause.
The expression total_due
is neither of the above.
Before version 5.7.5, MySQL used to accept such invalid queries. However, the server was free to return indeterminate values for the invalid expressions. Since version 5.7.5, MySQL rejects such queries (other RDBMSes reject them from long time ago...).
Why is such a query invalid?
Because a GROUP BY
query does not return rows from the table. It creates the rows it returns. For each row it puts in the result set it uses a group of rows from the table. All rows in the group have the same values for the expressions present in the GROUP BY
clause but they may have distinct values in the other expressions that appear in the SELECT
clause.
What's the correct solution for this particular question?
I answered this question many times before on StackOverflow. Take a look at this answer, this answer, this answer or this answer and apply to your query what you learn from there.