我正在尝试回答一个具体问题:““运动”类别中哪部电影最受欢迎?” 我已经尝试过
WITH CustomerRentalsPerStore AS
(
SELECT R.customer_id, I.category_id, COUNT (R.inventory_id) as rental_count
from rental AS R
INNER JOIN inventory AS I
on R.inventory_id = I.inventory_id
GROUP BY customer_id, I.category_id
--ORDER BY COUNT (R.inventory_id) desc
)
SELECT c.customer_id, c.first_name, c.last_name, cr.rental_count, cr.store_id
FROM Customer C
INNER JOIN CustomerRentalsPerStore CR
on C.customer_id = CR.customer_id
where cr.rental_count = (SELECT MAX(rental_count) FROM CustomerRentalsPerStore)
AND CR.category_id='Sports'
以下是ER图:
任何帮助将不胜感激!谢谢
答案 0 :(得分:0)
根据您为我澄清的运动类电影中租金最高的电影 ,我有以下 estested SQL应该可以为您提供结果:
SELECT f.title, COUNT(*) AS RentalCount
FROM film f
INNER JOIN film_category fc ON fc.film_id = f.film_id
INNER JOIN category c ON c.category_id = fc.category_id
INNER JOIN inventory i ON i.film_id = f.film_id
INNER JOIN rental r ON r.inventory_id = i.inventory_id
WHERE (c.name = 'Sports')
GROUP BY f.title
ORDER BY 2 DESC;
这可以有效地获得“体育”类别中所有电影的所有租赁次数(COUNT
)。显然,您只希望第一个结果,因此仅将输出限制为一行。
该代码未经测试,但应为您指明正确的方向。
答案 1 :(得分:0)
另一种方法是在进入GROUP BY
和COUNT(*)
处理之前,首先使选择尽可能小/限制。
优化器可能会选择一种更好的执行方法,但这取决于索引。
SELECT
film.title
, COUNT(*)
FROM (
SELECT
category.category_id
FROM
category
INNER JOIN
film_category
ON
category.category_id = film_category.category_id
INNER JOIN
film
ON
film_category.category_id = film.film_id
INNER JOIN
inventory
ON
film.film_id = inventory.film_id
INNER JOIN
rental
ON
inventory.film_id= rental.inventory_id
WHERE
category.name = 'Sports'
) AS alias
INNER JOIN
film
ON
alias.film_id = film.film_id
GROUP BY
film.title
ORDER BY
COUNT(*) DESC
LIMIT 1