如何对我的每个案件强制执行限制

时间:2014-02-02 18:47:07

标签: mysql

以下是我的查询

$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个以上。

如果可能的话,我希望在单个选择中完成所有操作,而不是多个选择。这是由于数据集快速变化。

1 个答案:

答案 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;