问题
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
回答1:
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.
回答2:
group by id will roll all the rows in attproduct that are associated with a given id into one result row. If you don't specify an aggregator like min or max, a random value from the source rows will be selected for the result (likely the first found).
来源:https://stackoverflow.com/questions/15354963/mysql-if-with-max