Skip to content
Advertisement

How to tell MariaDB/MySQL that a column is unique due to HAVING clause

With ONLY_FULL_GROUP_BY set (which I don’t want to/can’t change) the following query errors with

ERROR 1055 (42000): ‘dbname.test1.person_id’ isn’t in GROUP BY

(or equivalent longer message in mariadb).

How can I “tell” MySQL that I know the person_id is unambiguous because of the HAVING clause? I don’t want to use ANY_VALUE because that isn’t available in all the dbs where this code needs to run.

Edit: It has been rightly pointed out that something like MAX will work on person_id here but the MAX value of a person_id doesn’t really make sense and feels fragile to future changes. Is there a better way of structuring the query so that isn’t necessay?

Advertisement

Answer

One way to solve this is to use a subquery to find all the things that are unique to one person:

and then grab the details we actually want in the outer query now we know which things we care about:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement