0

我完全被我的家庭作业困住了。我正在使用 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,这是人数,而不是租借的恐怖电影。在这一点上,我的逻辑只是让我失望。请帮忙!

4

3 回答 3

1

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

如果您想使用 COUNT,您还需要使用GROUP BY来实现聚合计数。

您还可以查看带有HAVING子句的GOUP BY 。

于 2013-03-05T20:54:36.830 回答
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
于 2013-08-05T20:26:12.197 回答
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
于 2017-10-26T11:23:24.380 回答