How to fix query group with only_full_group_by

后端 未结 1 1076
既然无缘
既然无缘 2020-12-18 07:27

I have a basic key-value table, that has some data in it for each user. With the updated mysql it has the sql_mode set to only_full_group_by (new d

相关标签:
1条回答
  • 2020-12-18 08:12

    This is a common error for MySQL users. In MySQL 5.7, by default the database enforces the standard semantics that most other SQL databases have been enforcing for years.

    The rule is that every column in your select-list must be one of:

    • Named in the GROUP BY clause; i.e. it's what you are grouping be.
    • Inside an aggregate function like MIN, MAX(), SUM(), GROUP_CONCAT(), etc.
    • Functionally dependent on the column you are grouping by (this is MySQL's extension to standard SQL behavior, and other SQL databases don't necessarily support this).

    In your query (I'll expand your SELECT *):

    select user_id, feature_key, feature_value from user_features
    where user_id = 1
    group by feature_key
    

    You are grouping by feature_key, but this means the other columns don't comply with the rules I described above.

    Here's a way to fix it:

    select MAX(user_id), feature_key, GROUP_CONCAT(feature_value)
    from user_features
    where user_id = 1
    group by feature_key
    

    It might seem redundant to use MAX(user_id) since there is only one value possible based on the WHERE clause condition. But there's no harm either. MIN(user_id) would also work.

    See also my past answers on this same error:

    • https://stackoverflow.com/a/47701851/20860
    • https://stackoverflow.com/a/38705647/20860
    0 讨论(0)
提交回复
热议问题