[英]mysql group by with where returns totally other results
I try to select in a one to many relation childs where records of childs is 1. For fetching childs with one record I use the following query. 我尝试从一对多的关系子项中选择子项记录为1的子项。要获取一条记录的子项,请使用以下查询。
Here is the simple query which works if I do not use where
statement 如果我不使用
where
语句,这是一个简单的查询
select a.iid,
account_id,
count(*) as props
from accounts_prop a
group by a.account_id
having props = 1
when I use where
I get back totally other result. 当我使用
where
我回来完全其他结果。 In this case I get records which shows that props are having 1 record but actually having more than one 在这种情况下,我得到的记录表明道具有1条记录,但实际上有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
What I'm missing in this case 在这种情况下我所缺少的
the where condition filter you original rows so 条件条件将原始行过滤为
where a.von >= '2017-08-25'
reduce the number of rows involved in query 减少查询涉及的行数
the having clause work on the result of a query so in you have filter with a where (or not ) you obtain different result haveing子句处理查询的结果,因此在具有where(或not)的过滤器时,您将获得不同的结果
In your case in the first query your count is calculate on all the rows in your in the second query your count is calculated only on a subset 在您的情况下,在第一个查询中,您的计数是在第二个查询中的所有行上计算的,您的计数仅在一个子集上计算
This can explain why you obtain different resul from the two query 这可以解释为什么您从两个查询中获得不同的结果
Upon closer inspection, your original query is not even determinate: 经过仔细检查,您的原始查询甚至无法确定:
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
The query makes no sense because you are selecting the iid
column while aggregating on other columns. 该查询没有意义,因为您正在选择
iid
列,同时在其他列上进行聚合。 Which value of iid
should be chosen for each account? 每个帐户应选择哪个
iid
值? This is not clear, and your query would not even run on certain versions of MySQL or most other databases. 这尚不清楚,您的查询甚至无法在某些版本的MySQL或大多数其他数据库上运行。
Instead, put your logic to find accounts with only a single record into a subquery, and then join to that subquery to get the full records for each match: 相反,将您的逻辑放在子查询中查找仅具有一条记录的帐户,然后加入该子查询以获取每个匹配项的完整记录:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.