2014-04-03 18 views
0

我有這個疑問:MYSQL集團通過情況,即隨着多列

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個值語句。

+0

給那些沒有理由投票-1的人:我不是mysql專家。我需要一些幫助。 – albanx

回答

-2

GROUP BY中不能有CASE

如果無論出於何種原因(*?),您需要對一些記錄進行分組,並將其他記錄取消分組,則請使用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的功能。

+0

謝謝你的回答。我解決了以下這個建議:http://stackoverflow.com/questions/3490877/trouble-with-group-by-case?rq=1 – albanx

+0

基本上我的問題是,我需要根據custom_field_set_id值 – albanx

+4

「你不能在GROUP BY中有CASE這是不正確的。您絕對可以在GROUP By中擁有CASE語句。 – Nate