mysql if() with max()

丶灬走出姿态 提交于 2021-02-08 10:00:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!