题目:
自寻。
解题思路:
通过union或union all 把两个独立的搜索结果合起来就行了。
1.group 里 不能用 聚合函数。
select user_id,count(user_id)as count from MovieRating group by user_id,count(user_id) order by count
这样 才是对的
select user_id,count(user_id)as count from MovieRating group by user_id order by count
1056 -Can't group on 'cou nt(user_id)’.
应该是group 里 不能用 聚合函数。
2.这里的 as results 为啥是不对的?
select name,count(user_id)as count from MovieRating group by name order by count,title limit 1 as results
GPT给的回复是,limit已经限定了返回结果集的行数,不能再给results了。
其实是我results 位置加的不对。像下面这个加的位置才是对的。
select t.name as results from
(select u.name,count(mr.user_id)as count from MovieRating mr left join Users u on u.user_id = mr.user_id group by mr.user_id order by count(mr.user_id)desc ,u.name limit 1 )t
3. between 时间的表述
不带这个不对。。
where mr.created_at between 2020-02-01 and 2020-02-28
要这样。
where mr.created_at between '2020-02-01' and '2020-02-28'
4.union all 和 union 区别
union 是去重,而union all 是不去重,全部的都显示出来。
5.根据【字典序】的排列
其实就是order by 栏名 ,如果它是字符串,它会自己根据字典序排列的。
参考答案:
select t.name as results from
(select u.name,count(mr.user_id)as count from MovieRating mr left join Users u on u.user_id = mr.user_id group by mr.user_id order by count(mr.user_id)desc ,u.name limit 1 )t
union all
select p.title as results from (
select mi.title,mr.movie_id,avg(mr.rating) as score from MovieRating mr left join Movies mi on mr.movie_id = mi.movie_id
where mr.created_at between '2020-02-01' and '2020-02-28'
group by mr.movie_id order by avg(mr.rating) desc,title limit 1
) p