MySQL only_full_group_by
Error: A Comprehensive Guide
MySQL 5.7 introduced the only_full_group_by
SQL mode, leading to errors like this:
<code>Expression #1 of SELECT list is not in GROUP BY clause and contains non-aggregated column 'support_desk.mod_users_groups.group_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by</code>
This error arises because only_full_group_by
mandates that all columns in the SELECT
list, excluding aggregated columns, must also appear in the GROUP BY
clause. Previous MySQL versions didn't enforce this, potentially yielding ambiguous results.
Solutions and Troubleshooting
Here's how to address this issue:
1. Include the Column in GROUP BY
:
The simplest fix is adding the offending column (group_id
in this example) to your GROUP BY
clause:
... GROUP BY group_name, group_id ...
2. Aggregate or Use ANY_VALUE()
:
If you only need a single value from non-aggregated columns within each group, use aggregate functions like COUNT()
or SUM()
. Alternatively, ANY_VALUE()
returns an arbitrary value from the group:
SELECT ANY_VALUE(g.group_id) AS value, g.group_name AS text ...
3. Disable only_full_group_by
(Not Recommended):
You can disable this mode, but it's generally discouraged as it masks potentially problematic queries:
SET sql_mode = 'only_full_group_by=OFF';
Best Practices
g.group_id
) when using multiple tables to avoid ambiguity. A revised query might look like this:SELECT g.group_id AS value, g.group_name AS text FROM mod_users_groups g LEFT JOIN mod_users_data d ON g.group_id = d.group_id ...
group_id
and group_name
are unique within their respective groups to prevent unexpected results from duplicate values.By following these steps, you can effectively resolve only_full_group_by
violations and write more robust and predictable MySQL queries.
The above is the detailed content of How to Resolve the MySQL 'only_full_group_by' Error?. For more information, please follow other related articles on the PHP Chinese website!