题解 | #统计复旦用户8月练题情况#
统计复旦用户8月练题情况
https://www.nowcoder.com/practice/53235096538a456b9220fce120c062b3
select
a.device_id,
university, //需改进
count(question_id) question_cnt,
sum(if(result = 'right', 1, 0)) right_question_cnt
from
user_profile a
left join question_practice_detail b
on a.device_id = b.device_id
and month (date) = 8
where
university = '复旦大学'
group by
a.device_id;
在MySQL8.0+版本中,默认情况下,select语句中的列必须出现在group by子句中或被包含在聚合函数中,否则会导致查询报错, 这是为了确保查询结果的确定性和一致性.
上述查询university列并未出现在group by子句中,根据SQL标准,这种查询是无效的,除非university在每个device_id下都有相同的值.若university和device_id字段是1:1或1:n关系,则这条查询可能能正确返回结果,但这仅是因为数据的特性,而不是查询语法的正确性.
改进(确保university在每个device_id下是一致的):
- university选项改成:'复旦大学' university 或: MAX(university) university
- 结尾改成:group by a.device_id, a.university

