尝试列出表1中的所有内容并在表2中进行记录
表一的每一行都有一个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
我当前的问题是未显示来自table1的行,其中table2中的记录为0
您想要的查询是:
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;
更改如下:
t2.deleted
已移至该on
子句。否则,这会将外部联接变成内部联接。t1.deleted
仍然保留在where
子句中,因为大概您确实希望将此作为过滤条件。group by
子句基于t1.id
,因为t2.idintable1
将NULL
在没有匹配项时出现。t1.id
假设在中id
是唯一的(或主键),则只需使用即可table1
。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句