Search code examples
mysqlentity-attribute-value

mysql if() with max()


I have a table named attproduct:

there are three columns id, attribute, values.

I have color and brand for each id in attribute column and corresponding values in value column

SELECT id, MAX( IF( attribute =  'brand', value, NULL ) ) AS Brand,
       MAX( IF( attribute =  'color', value, NULL ) ) AS color
FROM fy.attproduct
GROUP BY id

When I run this query i get output as desired in id, brand, color as columns.

I need to know what is role of max in my query, when i remove max, i get null values


Solution

  • MAX() is combining the values associated with each id.

    SELECT id, IF( attribute =  'brand', value, NULL ) AS Brand, IF( attribute =  'color', value, NULL ) AS color
    FROM fy.attproduct
    

    without the GROUP BY should return rows like

    ID  Brand      color
    1   'mybrand'  NULL
    1   NULL       'mycolor'
    

    When MAX() is not used, only one of the rows will be chosen, so at least one column will be NULL.