组和子查询问题
Group and subquery issue
这是我的示例数据
CREATE TABLE customer1
(
rating int(9),
genre varchar(100),
title varchar(100)
);
INSERT INTO customer1 (rating, genre, title)
VALUES
(2, 'A', 'abc'),
(4, 'A', 'abc1'),
(2, 'B', 'abc2'),
(3, 'B', 'abc3'),
(2, 'C', 'abc4'),
(5, 'C', 'abc5');
我需要找到每个类型中评分最高的影片。
感谢您的帮助。
一个选项使用子查询进行过滤:
select c.*
from customer1
where c.rating = (select max(c1.rating) from customer1 c1 where c1.genre = c.genre)
这将利用 (genre, rating)
上的索引。
在MySQL8.0中,您还可以使用window函数:
select *
from (
select c.*,
rank() over(partition by genre order by rating desc) rn
from customer1 c
) c
where rn = 1
这是我的示例数据
CREATE TABLE customer1
(
rating int(9),
genre varchar(100),
title varchar(100)
);
INSERT INTO customer1 (rating, genre, title)
VALUES
(2, 'A', 'abc'),
(4, 'A', 'abc1'),
(2, 'B', 'abc2'),
(3, 'B', 'abc3'),
(2, 'C', 'abc4'),
(5, 'C', 'abc5');
我需要找到每个类型中评分最高的影片。
感谢您的帮助。
一个选项使用子查询进行过滤:
select c.*
from customer1
where c.rating = (select max(c1.rating) from customer1 c1 where c1.genre = c.genre)
这将利用 (genre, rating)
上的索引。
在MySQL8.0中,您还可以使用window函数:
select *
from (
select c.*,
rank() over(partition by genre order by rating desc) rn
from customer1 c
) c
where rn = 1