以下是我的查询
$sql="SELECT sum(`total`) as `total`, `a`, `type`
FROM `table`
GROUP BY `a`, `type`
ORDER BY `type`,
CASE WHEN `type`='type1' THEN `a` END ASC,
CASE WHEN `type`='type2' THEN `a` END DESC LIMIT 15
这符合我的预期。但我想要type1的15和type2的15。相反,我得到类型1的5和类型2的10,即使type1和type2各有15个以上。
如果可能的话,我希望在单个选择中完成所有操作,而不是多个选择。这是由于数据集快速变化。
答案 0 :(得分:4)
union all
可能是获得所需内容的最简单方法:
(SELECT sum(`total`) as `total`, `a`, `type`
FROM `table`
WHERE `type`= 'type1'
GROUP BY `a`
ORDER BY `a` desc
LIMIT 15
) union all
(SELECT sum(`total`) as `total`, `a`, `type`
FROM `table`
WHERE `type`= 'type2'
GROUP BY `a`
ORDER BY `a` desc
LIMIT 15
)
order by `type`, `a` desc;