mysql group by with where returns 完全是其他结果

mysql group by with where returns totally other results

我尝试 select 在孩子记录为 1 的一对多关系孩子中。为了使用一条记录获取孩子,我使用以下查询。

如果我不使用 wherestatement

,这是一个简单的查询
select a.iid, 
account_id,
count(*) as props

from  accounts_prop a
group by a.account_id
having props = 1

当我使用 where 时,我得到了完全不同的结果。在这种情况下,我得到的记录显示道具有 1 条记录但实际上有不止一条

    select a.iid, 
    account_id,
    count(*) as props

    from   accounts_prop a
    where a.von >= '2017-08-25'
    group by a.account_id

having props = 1

在这种情况下我缺少什么

经过仔细检查,您的原始查询甚至不确定:

SELECT
    a.iid,              -- OK, but which value of iid do we choose?
    a.account_id,
    COUNT(*) AS props
FROM accounts_prop a
GROUP BY a.account_id
HAVING props = 1

查询没有意义,因为您在对其他列进行聚合时选择了 iid 列。 应该为每个帐户选择 iid 的哪个 值?这还不清楚,您的查询甚至不会 运行 在某些版本的 MySQL 或大多数其他数据库上。

相反,将查找只有一条记录的帐户的逻辑放入子查询中,然后加入该子查询以获取每个匹配项的完整记录:

SELECT a1.*
FROM accounts_prop a1
INNER JOIN
(
    SELECT account_id
    FROM accounts_prop
    GROUP BY account_id
    HAVING COUNT(*) = 1
) a2
    ON a1.account_id = a2.account_id
WHERE a1.von >= '2017-08-25'

where 条件过滤原始行,因此

 where a.von >= '2017-08-25'

减少查询涉及的行数

having 子句作用于查询的结果,因此在您使用带有 where(或不带 where)的过滤器时,您会获得不同的结果
在你的情况下,在第一个查询中,你的计数是在你的第二个查询中的所有行上计算的,你的计数仅在一个子集上计算

这可以解释为什么你从两个查询中得到不同的结果