mysql group by和where返回完全其他结果
我尝试在一对多关系中选择childs,其中childs的记录为1。对于使用一条记录获取child,我使用以下查询 如果我不使用mysql group by和where返回完全其他结果,mysql,one-to-many,children,records,Mysql,One To Many,Children,Records,我尝试在一对多关系中选择childs,其中childs的记录为1。对于使用一条记录获取child,我使用以下查询 如果我不使用where语句,下面是一个简单的查询 select a.iid, account_id, count(*) as props from accounts_prop a group by a.account_id having props = 1 当我使用where时,我得到了完全不同的结果。在本例中,我得到的记录显示道具有1条记录,但实际上有多条记录 se
where
语句,下面是一个简单的查询
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(或not)的过滤器时,您可以获得不同的结果在第一个查询中,对所有行进行计算;在第二个查询中,仅对子集进行计算
这可以解释为什么您从两个查询中获得不同的结果。两个查询不同。第一个查询涉及所有行,第二个查询仅涉及a.von>=“2017-08-25”的行,然后您有不同的行集合进行分组。。你的问题不清楚。。试着解释清楚