【发布时间】:2020-02-29 19:58:54
【问题描述】:
表格:
create table movies (
movie_id int primary key,
title varchar(50));
insert into movies values
(1, 'avengers'), (2, 'frozen2'), (3, 'joker');
create table users (
user_id int primary key,
name varchar(50));
insert into users values
(1, 'daniel'), (2, 'monica'), (3, 'maria'), (4, 'james');
create table movie_rating (
movie_id int,
user_id int,
rating int,
created_at date,
primary key (movie_id, user_id));
insert into movie_rating values
(1, 1, 3, '2020-01-12'),
(1, 2, 4, '2020-02-11'),
(1, 3, 2, '2020-02-12'),
(1, 4, 1, '2020-01-01'),
(2, 1, 5, '2020-02-17'),
(2, 2, 2, '2020-02-01'),
(2, 3, 2, '2020-03-01'),
(3, 1, 3, '2020-02-22'),
(3, 2, 3, '2020-02-25');
问题:编写如下 SQL 查询:
查找对电影评分最多的用户的姓名。 如果出现平局,则返回按字典顺序较小的用户名。
找出 2020 年 2 月平均评分最高的电影名称。 如果出现平局,则返回按字典顺序较小的电影名称。
查询分2行返回,以上表格的查询结果格式为:
Result table:
+--------------+
| results |
+--------------+
| daniel |
| frozen 2 |
+--------------+
只有当我在union 之前和之后添加括号时,我的以下解决方案才有效。
(select u.name results
from users u join movie_rating m on u.user_id = m.user_id
group by m.user_id, u.name
order by count(rating) desc, name
limit 1)
union
(select m.title results
from movies m join movie_rating r
on m.movie_id = r.movie_id
and r.created_at between '2020-02-01' and '2020-02-29'
group by r.movie_id, m.title
order by avg(r.rating) desc, m.title
limit 1);
如果我没有括号,我会得到错误。为什么我必须使用括号才能使union 工作?
select u.name results
from users u join movie_rating m on u.user_id = m.user_id
group by m.user_id, u.name
order by count(rating) desc, name
limit 1
union
select m.title results
from movies m join movie_rating r
on m.movie_id = r.movie_id
and r.created_at between '2020-02-01' and '2020-02-29'
group by r.movie_id, m.title
order by avg(r.rating) desc, m.title
limit 1;
ERROR: syntax error at or near "union"
LINE 6: union
^
【问题讨论】:
标签: sql postgresql sql-order-by union