[英]SQL Count + Left join + Group by … Missing rows
Trying to list all what's in table 1 and records under it in table 2 尝试列出表1中的所有内容并在表2中进行记录
Table one each row has an id , and each row in table 2 has idontable1 表一的每一行都有一个id,表2的每一行都有idontable1
select table1.*, count(table2.idintable1)as total
from table1
left join table2 on table1.id=table2.idintable1
WHERE table1.deleted='0' AND table2.deleted=0
group by
table2.idintable1
My current problem is rows from table1 with 0 records in table2 are not displayed I want them to be displayed 我当前的问题是未显示来自table1的行,其中table2中的记录为0
The query that you want is: 您想要的查询是:
select t1.*, count(t2.idintable1) as total
from table1 t1 left join
table2 t2
on t1.id = t1.idintable1 and t2.deleted = 0
where t1.deleted = 0
group by t1.id;
Here are the changes: 更改如下:
t2.deleted
was moved to the on
clause. t2.deleted
上的条件已移至on
子句。 Otherwise, this turns the outer join into an inner join. t1.deleted
remains in the where
clause, because presumably you really do want this as a filter condition. t1.deleted
上的条件保留在where
子句中,因为大概您确实希望将此作为过滤条件。 group by
clause is based on t1.id
, because t2.idintable1
will be NULL
when there are no matches. group by
子句基于t1.id
,因为如果没有匹配t1.id
,则t2.idintable1
将为NULL
。 Just using t1.id
is fine, assuming that id
is unique (or a primary key) in table1
. id
在table1
是唯一的(或主键),则仅使用t1.id
。 You should GROUP BY table1.id
. 您应该
GROUP BY table1.id
。
The LEFT JOIN
ensures all the rows from table1
appear in the result set. LEFT JOIN
确保table1
中的所有行都出现在结果集中。 Those that do not have a pair in table2
will appear with NULL
in field table2.idintable1
. 在
table2
没有对的那些将在table2.idintable1
字段中显示为NULL
。 Because of that your original GROUP BY
clause produces a single row for all the rows from table1
that do not appear in table2
(instead of one row for each row of table1
). 因此,您原来的
GROUP BY
子句为table1
中所有未出现在table2
的行产生一行(而不是table1
每一行产生一行)。
You have fallen into mysql's non-standard group by support trap. 通过支持陷阱,您已经属于mysql的非标准组。
Change your group by to list all columns of table 1: 更改分组依据以列出表1的所有列:
group by table1.id, table1.name, etc
or list the column positions of all table1 columns in the select: 或在select中列出所有table1列的列位置:
group by 1, 2, 3, 4, etc
Or use a subquery to get the count vs the id, and join table1 to that. 或使用子查询获取计数与ID的关系,然后将table1与之连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.