Sakila db SQL找到租用了> 10部恐怖电影的客户

时间:2013-03-05 20:31:06

标签: mysql

我完全被我的作业困住了。我正在使用Sakila示例数据库。我本来应该写一个查询,它会给我一个已经租借了> 10部恐怖电影的所有客户的清单。这就是我到目前为止所做的:

select CONCAT(c.first_name, " ", c.last_name) AS "Customer name", 
FROM customer AS c

INNER JOIN rental AS r
ON c.customer_id = r.customer_id

inner join  inventory as i
on i.inventory_id = r.inventory_id

inner join  film_category as fc
on i.film_id = fc.film_id
 inner join 
(select * from category as ca
where ca.name = 'horror') as h
 on h.category_id = fc.category_id 
 ;

我可以让它返回已经租借恐怖电影的客户的所有(846),但我如何才能获得租用超过10部恐怖电影的客户?我知道我需要COUNT功能,但当我把它放入时,它会给我1个人,计数846,这是一个人数,而不是租来的恐怖电影。我的逻辑就是在这一点上让我失望。求救!

3 个答案:

答案 0 :(得分:1)

不幸的是,我不知道有问题的示例数据库,但我觉得答案不会影响我的回复。

如果您想使用COUNT,您还需要使用GROUP BY来获得总计数。

您还可以使用GOUP BY子句查看HAVING

答案 1 :(得分:1)

如果有人需要轻松用餐:

SELECT R.customer_id, COUNT(*) AS cnt 
FROM sakila.rental R LEFT JOIN sakila.inventory I ON R.inventory_id = I.inventory_id 
LEFT JOIN sakila.film F ON I.film_id = F.film_id 
LEFT JOIN sakila.film_category FC on F.film_id = FC.film_id 
LEFT JOIN sakila.category C ON FC.category_id = C.category_id 
WHERE C.name = "Horror" 
GROUP BY R.customer_id HAVING cnt > 10

答案 2 :(得分:0)

您也可以编写没有左连接/内连接的查询。请注意,没有超过10个恐怖租赁的客户,因此空白结果不应该让您感到困惑(尝试2并且它有效!)

SELECT cu.first_name, cu.last_name, COUNT(r.rental_id) as horror_film_count
FROM customer AS cu, rental AS r, inventory as i, film as f, category as ca, 
film_category as fc
WHERE cu.customer_id = r.customer_id 
AND r.inventory_id = i.inventory_id
AND i.film_id = f.film_id
AND f.film_id = fc.film_id
AND fc.category_id = ca.category_id
AND ca.category_id = 11
GROUP BY cu.customer_id
HAVING horror_film_count > 10