0

在 MySQL 中,我有一个表,其中有一列充满正整数,我想过滤掉所有奇数。MySQL文档中似乎没有任何内容。我尝试了以下查询。

select kapsule.owner_name, 
       kapsule.owner_domain, 
       count(xform_action) 
  from kapsule, rec_xform 
 where rec_xform.g_conf_id=kapsule.g_conf_id 
   and (count(xform_action))%2=0 
 group by kapsule.owner_name;

我只想保留那些 count(xform_action) 为偶数的值。桌子看起来像这样。

4

2 回答 2

0

COUNT(*)对于像使用这样的聚合函数,GROUP BY您需要使用HAVING子句

select kapsule.owner_name, kapsule.owner_domain, 
count(xform_action) from kapsule,   rec_xform 
where rec_xform.g_conf_id=kapsule.g_conf_id and 
group by kapsule.owner_name, kapsule.owner_domain
HAVING (count(xform_action))%2=0 

或者您可以使用别名(即 AS),例如:

select kapsule.owner_name, kapsule.owner_domain, 
count(xform_action) count_form from kapsule,   rec_xform 
where rec_xform.g_conf_id=kapsule.g_conf_id and 
group by kapsule.owner_name, kapsule.owner_domain
HAVING count_form%2=0 

并且您可以使用 JOIN 比旧的连接表更有效。顺便说一句,如果您有 GROUP BY 聚合函数之前的字段应该在 GROUP BY 中,例如:

select kapsule.owner_name, kapsule.owner_domain, 
count(xform_action) count_form from kapsule A
INNER JOIN rec_xform B
ON A.g_conf_id=B.g_conf_id and 
GROUP BY by A.owner_name, A.owner_domain
HAVING count_form%2=0 

在此处查看示例

于 2013-06-07T05:38:11.310 回答
0

GROUP BY要在需要使用HAVING子句 后过滤掉结果集。WHERE子句用于在GROUP BY发生之前过滤源行。

尝试

SELECT k.owner_name, 
       k.owner_domain, 
       COUNT(x.xform_action) cnt -- < you probably meant to use SUM() instead of COUNT() here
  FROM kapsule k JOIN rec_xform x -- < use JOIN notation for clarity
    ON x.g_conf_id = k.g_conf_id 
 GROUP BY k.owner_name
HAVING cnt % 2 = 0

您可能打算使用SUM()(对组中所有行的列的值求和)聚合而不是COUNT()(返回组中的行数)

这是SQLFiddle演示(适用于SUM()COUNT()

于 2013-06-07T05:38:27.090 回答