我有三张包含电影,评级和评论者数据的表格。我的数据的连接如下所示:
mysql root@localhost:foo> SELECT m.title, ra.stars, re.name
-> FROM Movie m
-> JOIN Rating ra ON m.mid = ra.mid
-> JOIN `Reviewer` re ON ra.rid = re.rid
-> ORDER BY m.title, ra.stars DESC;
+-------------------------+-------+------------------+
| title | stars | name |
+-------------------------+-------+------------------+
| Avatar | 5 | James Cameron |
| Avatar | 3 | Elizabeth Thomas |
| E.T. | 3 | Ashley White |
| E.T. | 2 | Chris Jackson |
| Gone with the Wind | 4 | Sarah Martinez |
| Gone with the Wind | 3 | Mike Anderson |
| Gone with the Wind | 2 | Sarah Martinez |
| Raiders of the Lost Ark | 4 | Brittany Harris |
| Raiders of the Lost Ark | 4 | Chris Jackson |
| Raiders of the Lost Ark | 2 | Brittany Harris |
| Snow White | 5 | Elizabeth Thomas |
| Snow White | 4 | Daniel Lewis |
| The Sound of Music | 3 | Chris Jackson |
| The Sound of Music | 2 | Brittany Harris |
+-------------------------+-------+------------------+
我想要实现的是按照标题对上面的表格进行分组,并获得给每部电影评分最高的评论者的姓名。结果应如下所示。
+-------------------------+-------+------------------+
| title | stars | name |
+-------------------------+-------+------------------+
| Avatar | 5 | James Cameron |
| E.T. | 3 | Ashley White |
| Gone with the Wind | 4 | Sarah Martinez |
| Raiders of the Lost Ark | 4 | Brittany Harris |
| Raiders of the Lost Ark | 4 | Chris Jackson |
| Snow White | 5 | Elizabeth Thomas |
| The Sound of Music | 3 | Chris Jackson |
+-------------------------+-------+------------------+
我在某种程度上坚持如何做到这一点。有人能指出我正确的方向吗?
编辑:我最初虽然包括星列(MAX(stars)
)上的其他聚合函数是微不足道的,但我无法使其正常工作。任何想法如何起作用?
答案 0 :(得分:2)
解决方案1: - 来自您的结果集:
SELECT A.*
FROM Your_Table A
JOIN(
SELECT title,MAX(stars) stars
FROM Your_Table
GROUP BY title
)B ON A.title = B.title AND A.stars = B.stars
第二个解决方案: - 来自您的表
SELECT m.title, ra.stars, re.name
FROM Movie m
JOIN(
SELECT R.*
FROM Rating R
JOIN(
SELECT mid
,MAX(stars) Stars
FROM Rating
GROUP BY mid
)D ON R.mid = D.mid AND R.Stars = D.Stars
)Ra ON m.mid = ra.mid
JOIN Reviewer re ON ra.rid = re.rid
答案 1 :(得分:1)
SELECT m.title, ra.stars, re.name
FROM Movie m
JOIN (SELECT mid,MAX(stars) AS stars FROM Rating GROUP BY mid) ra
ON m.mid = ra.mid
JOIN Rating ra1
ON ra1.mid = ra.mid AND ra1.star=ra.star
JOIN Reviewer re
ON ra1.rid = re.rid
ORDER BY m.title, ra.stars DESC;
答案 2 :(得分:1)
SELECT m.title, ra.stars, re.name
FROM Movie m
JOIN Rating ra ON m.mid = ra.mid
JOIN Reviewer re ON ra.rid = re.rid
JOIN
(SELECT m.title, max(ra.stars) as stars
FROM Movie m
JOIN Rating ra ON m.mid = ra.mid
GROUP BY m.title) c
ON c.title=m.title AND ra.stars=c.stars
ORDER BY m.title, ra.stars DESC
答案 3 :(得分:1)
以下代码对您有所帮助,
SELECT m.title, ra.stars, re.name
FROM Movie m
JOIN Rating ra ON m.mid = ra.mid
JOIN Reviewer re ON ra.rid = re.rid
WHERE ra.stars = ( SELECT MAX(ra1.stars) FROM Movie m1 JOIN Rating ra1 on m1.mid = ra1.mid WHERE m1.title = m.title)
ORDER BY m.title, ra.stars DESC;