我想学习网页开发,所以我建立了网站,用户可以在哪里投票看电影,并且在查询我需要的内容时遇到问题。我的表格如下:
--rtable--
+-----------+------------+------------+
| movieid | rating | userid |
+-----------+------------+------------+
| 1 | 9 | 27 |
| 2 | 8 | 27 |
| 1 | 10 | 31 |
| 1 | 7 | 42 |
| 2 | 8 | 31 |
+-----------+------------+------------+
--mtable--
+-----------+------------+------------+------------+
| movieid | moviename | movielink | director |
+-----------+------------+------------+------------+
| 1 | Foo | foo.com | bob |
| 2 | Bar | bar.com | steve |
+-----------+------------+------------+------------+
我想查询电影名称,电影链接,平均(评级)和用户评分(如果存在),按平均值下降(评级)
--desiredtable (if userid == 42)--
+-----------+------------+------------+------------+
| moviename | movielink | avgrating | yourrating |
+-----------+------------+------------+------------+
| Foo | foo.com | 8.66 | 7 |
| Bar | bar.com | 8 | NULL |
+-----------+------------+------------+------------+
我已经成功获得了moviename + movielink + avgrating与OUTER LEFT JOIN一起工作,但我正在摸索如何添加你的作品。我已经尝试过加倍使用OUTER JOIN并使用子查询,但似乎无法让它工作。
这是我到目前为止的工作
SELECT mtable.moviename, mtable.movielink, ROUND(AVG(rtable.rating), 2) AS avgrating,
FROM mtable LEFT OUTER JOIN rtable ON rtable.movieid = mtable.movieid GROUP BY mtable.charid ORDER BY AVG(rtable.rating) DESC
答案 0 :(得分:0)
您需要在mtable上加入rtable两次,一次获得平均值的所有评分,一次获得用户的评分。您还需要在on子句中提供已过滤r2的用户标识。 on子句中的过滤条件仅适用于r2,而不适用于整个数据集。
SELECT mtable.moviename, mtable.movielink, ROUND(AVG(r1.rating), 2) AS avgrating, max(r2.rating) as yourrating
FROM mtable m LEFT OUTER JOIN rtable r1 ON r1.movieid = m.movieid
LEFT JOIN rtable r2 on r2.movieid=m.movieid and r2.userid=...
GROUP BY m.movieid, m.moviename, m.movielink
ORDER BY AVG(r1.rating) DESC