题解 | #统计复旦用户8月练题情况#
统计复旦用户8月练题情况
http://www.nowcoder.com/practice/53235096538a456b9220fce120c062b3
我们有的时候直接使用左连接查询,当右表不存在该数据的时候,是可以查出带有null的列。可是当在where条件中有右表相关的筛选条件时,我们惊奇的发现查询的结果不带null值了,换句话说就是查出来的结果比预期的少。
把筛选条件放到连接处,通过on ... and ... 的方式,在连接时就附带上条件,此时不符合条件的数据列还是以null值的方式展现,并不会被后续的where筛选条件给筛选掉。
把筛选条件放到连接处,通过on ... and ... 的方式,在连接时就附带上条件,此时不符合条件的数据列还是以null值的方式展现,并不会被后续的where筛选条件给筛选掉。
select a.device_id,a.university, sum(case when b.question_id is null then 0 else 1 end) as question_cnt, sum(case when b.question_id is null then 0 when b.result='wrong' then 0 else 1 end) as right_question_cnt from user_profile a left join question_practice_detail b on(a.device_id=b.device_id and date_format(b.date,'%Y%m')='202108') where a.university='复旦大学' group by a.device_id,a.university #错误:(左表有数据右表无数据,结果没有显示对应Null值) #select a.device_id,a.university,b.question_id,b.result #from user_profile a #left join question_practice_detail b on(a.device_id=b.device_id) #where a.university='复旦大学' and date_format(b.date,'%Y%m')='202108' #正确:(左表有数据右表无数据,结果显示对应Null值) #select a.device_id,a.university,b.question_id,b.result #from user_profile a #left join question_practice_detail b on(a.device_id=b.device_id and date_format(b.date,'%Y%m')='202108') #where a.university='复旦大学'