简体   繁体   English

SQL计数+左联接+分组依据…缺少行

[英]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: 更改如下:

  • The condition on t2.deleted was moved to the on clause. t2.deleted上的条件已移至on子句。 Otherwise, this turns the outer join into an inner join. 否则,这会将外部联接变成内部联接。
  • The condition on t1.deleted remains in the where clause, because presumably you really do want this as a filter condition. t1.deleted上的条件保留在where子句中,因为大概您确实希望将此作为过滤条件。
  • The 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 . 假设idtable1是唯一的(或主键),则仅使用t1.id
  • The table aliases are not strictly necessary, but they make queries easier to write and to read. 表别名不是严格必需的,但是它们使查询更易于编写和阅读。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM