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).

CREATE TABLE test1 (
    thing VARCHAR(16),
    person_id INT
);

SELECT
    thing,
    person_id
FROM
    test1
GROUP BY
    thing
HAVING
    COUNT(DISTINCT person_id) = 1

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:

SELECT                  
    thing      
FROM          
    test1      
GROUP BY          
    thing     
HAVING         
    COUNT(DISTINCT person_id) = 1

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

SELECT 
    person_id, 
    thing 
FROM 
    test1 
WHERE 
    thing IN 
        (
            SELECT                  
                thing      
            FROM          
                test1      
            GROUP BY          
                thing     
            HAVING         
                COUNT(DISTINCT person_id) = 1
        )
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement