MYSQL Group By With Case WHEN具有多列

时间:2014-04-03 14:24:34

标签: mysql group-by case-when

我有这个问题:

SELECT `c`.*, `cont_prod`.`custom_field_set_id` AS `custom_field_set_id`,
 `cont_link_cont`.`id` AS `product_text_id`,
 `cf_321`.`value` AS `concept_number`,
 `cf_322`.`value` AS `annee`,
 `cf_323`.`value` AS `saison`,
 `cf_334`.`value` AS `color_id` 
FROM `container` AS `c` 
INNER JOIN `container_product` AS `cont_prod` 
ON c.id = cont_prod.container_id 
INNER JOIN `container_link` AS `cont_link` 
ON cont_prod.container_id = cont_link.container_id 
INNER JOIN `container` AS `cont_link_cont` 
ON cont_link_cont.id = cont_link.link_id  
LEFT JOIN `custom_field_string` AS `cf_321` 
ON cont_link_cont.id = cf_321.container_id 
AND cf_321.custom_field_id=321 
LEFT JOIN `custom_field_string` AS `cf_322` 
ON cont_link_cont.id = cf_322.container_id 
AND cf_322.custom_field_id=322 
LEFT JOIN `custom_field_string` AS `cf_323` 
ON cont_link_cont.id = cf_323.container_id 
AND cf_323.custom_field_id=323 
LEFT JOIN `custom_field_int` AS `cf_334` 
ON cont_link_cont.id = cf_334.container_id 
AND cf_334.custom_field_id=334 
WHERE `c`.`container_class` 
IN ('product') AND c.deleted = 0 
AND cont_link.reason ='product_main_text' 
AND cont_link_cont.container_class='product_text' 
AND cont_link_cont.hidden = 0 
GROUP BY CASE 
    WHEN custom_field_set_id=33 THEN cf_321.value,cf_322.value,cf_323.value,cf_334.value
END

但它不起作用。 基本上,当满足某些条件时,我需要按n个字段进行分组。 这个查询有什么问题:

GROUP BY CASE 
  WHEN custom_field_set_id=33 THEN cf_321.value,cf_322.value,cf_323.value,cf_334.value
END

修改 所以我期待与此小组相同的结果:

GROUP BY cf_321.value,cf_322.value,cf_323.value,cf_334.value

EDIT2解决方案:

GROUP BY 
CASE WHEN custom_field_set_id=33 THEN cf_321.value END,
CASE WHEN custom_field_set_id=33 THEN cf_322.value END,
CASE WHEN custom_field_set_id=33 THEN cf_323.value END,
CASE WHEN custom_field_set_id=33 THEN cf_334.value END

这是因为这里写的Trouble with GROUP BY CASE CASE WHEN只能返回1个值语句。

1 个答案:

答案 0 :(得分:-2)

CASE中无法GROUP BY

如果出于某种原因(*?),您需要将某些记录分组并将其他记录分组,请使用UNION

select stuff from container join other_stuff
where 
custom_field_set_id != 33
-- NO GROUP BY

UNION  -- or UNION ALL

select stuff from container join other_stuff
where 
custom_field_set_id = 33
GROUP BY pertinent_fields

(*?)您没有使用可以使用GROUP BY的函数。