这是我正在开发的电影租赁平台的基本摘录。为了向您展示,我只需要这三个表。
电影
Title | Genre |
-------------+---------------+
Why Me | Romantic |
The ET | Fantasy |
... | ... |
Planet | Documentary |
用户
ID | Name |
-------------+---------------+
213 | Jonh D |
34267 | Smith E |
... | ... |
256 | Sally F |
租金
User_ID | Film_Title | Date |
-------------+---------------+-------------+
34267 | The ET | 2015-11-01 |
256 | Planet | 2014-12-03 |
... | ... | ... |
256 | Why Me | 2016-03-04 |
就是说,我需要执行一个 SQL 查询,将每个 Film.Genre
和租用该类型电影数量最多的 User.Name
相关联。
ID | Genre |
-------------+---------------+
Sally F | Romantic |
Smith E | Fantasy |
... | ... |
Sally F | Documentary |
我会发布一些我的尝试,但老实说,我没有提出任何几乎没有意义的东西。我知道使用 JOIN
语句比尝试使用嵌套语句构建它更容易,但我很困惑,这太令人沮丧了。
SELECT u.Name, f.Genre
FROM User AS u JOIN Rent AS r JOIN Film AS f
GROUP BY f.Genre
ORDER BY(COUNT(r.User_ID))
最佳答案
这是假设流派字段在您的 rentals 表中:
select user_id, genre, max(rentals) from
(select
user_id,
genre,
count(*) as rentals
from rent group by user_id, genre)
group by user_id, genre;
关于mysql - 三张表之间的SQL查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41487758/