在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)为偶数的值。该表看起来像这样。
答案 0 :(得分:0)
对于使用COUNT(*)
的{{1}}等汇总函数,您需要使用GROUP BY
子句
HAVING
或者你可以使用别名(即AS),如:
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
你可以使用JOIN比连接表的旧效率更高效。顺便说一下 如果您在聚合函数应该在GROUP BY之前具有GROUP BY字段,那么:
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
参见示例here
答案 1 :(得分: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()
)