質問

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

役に立ちましたか?

解決

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.

他のヒント

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top