[英]SQL How to find which customer has rented the most films?
I'm struggling with a question that said Which customer has rented the most films?我正在努力解决一个问题,即哪个客户租借的电影最多?
I am doing this using the Seikila sample database in MySQL.我正在使用 MySQL 中的 Seikila 示例数据库执行此操作。 I have something that joins my tables together and attempts to give me a count but I know its wrong just looking at the actual data in the rental table.
我有一些东西可以将我的表连接在一起并试图给我一个计数,但我知道只是查看租赁表中的实际数据是错误的。 my code is as below
我的代码如下
SELECT r.rental_id, cust.customer_id, count(*) as Total_Rentals
FROM rental as r
INNER JOIN customer AS cust on r.customer_id = cust.customer_id
GROUP BY cust.customer_id;
but it tells me for example customer 1 has rented 32 movies, which I know is wrong.但它告诉我例如客户 1 租了 32 部电影,我知道这是错误的。 what am I doing wrong?
我究竟做错了什么? since I was asked for clarification, the database I am using is: https://dev.mysql.com/doc/sakila/en/
由于我被要求澄清,我使用的数据库是: https : //dev.mysql.com/doc/sakila/en/
And I am trying to find which customer has rented the most films, I am not entirely sure what my script is actually returning.我试图找出哪个客户租借了最多的电影,我不完全确定我的剧本实际上返回了什么。
Remove the column rental_id
from the select list and sort the result by count(*)
descending to return the top 1 row:从选择列表中删除列
rental_id
count(*)
降序对结果进行排序以返回前1 行:
SELECT cust.customer_id, cust.name, count(*) as Total_Rentals
FROM rental as r
INNER JOIN customer AS cust on r.customer_id = cust.customer_id
GROUP BY cust.customer_id, cust.name
ORDER BY Total_Rentals DESC LIMIT 1
But if you only need the customer's id then there is no need for a join:但是,如果您只需要客户的 id,则不需要加入:
SELECT customer_id, count(*) as Total_Rentals
FROM rental
GROUP BY customer_id
ORDER BY Total_Rentals DESC LIMIT 1
You need to join
customer
and rental
, group by
customer
id (without rental
id) and count it:您需要
join
customer
和rental
, group by
customer
id group by
(不带rental
id)并计数:
SELECT cust.customer_id, count(*) as Total_Rentals
FROM rental as r
INNER JOIN customer AS cust on r.customer_id = cust.customer_id
GROUP BY cust.customer_id;
So this code should work.所以这段代码应该可以工作。 If it doesn't work, that probably means that you have duplicates or other nonconventional issues.
如果它不起作用,那可能意味着您有重复或其他非常规问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.