我想找一部租得最多的没有使用限制的电影。我试图使用以下查询:

SELECT f.title, f.film_id
FROM film f
JOIN inventory i ON f.film_id = i.film_id
JOIN rental r ON r.inventory_id = i.inventory_id
GROUP BY f.film_id
HAVING COUNT(r.rental_id) = MAX(
    SELECT COUNT(r2.rental_id)
    FROM rental r2, inventory i2
    WHERE i2.inventory_id = r2.inventory_id
    GROUP BY i2.film_id);

但是mySQL告诉我这里有语法错误,但是当我独立运行子查询时,它返回期望的表。我做错了什么吗?
相关数据库架构:
film(film  id, title, description, release year, language id, original language id, rental duration, rental rate, length, replacement cost, rating, special features, last update)
inventory(inventory id, film id, store id, last update)
rental(rental id, rental date, inventory id, customer id, return date, staff id, last update)

最佳答案

不能对结果集使用MAX(),但可以使用

someValue >= ALL (subquery)

因为ALL要求前面的运算符对于集合中的所有值都为true,所以要实现您正在尝试的操作。
试试这个:
SELECT f.title, f.film_id
FROM film f
JOIN inventory i ON f.film_id = i.film_id
JOIN rental r ON r.inventory_id = i.inventory_id
GROUP BY f.film_id
HAVING COUNT(r.rental_id) >= ALL (
    SELECT COUNT(r2.rental_id)
    FROM rental r2, inventory i2
    WHERE i2.inventory_id = r2.inventory_id
    GROUP BY i2.film_id);

07-27 18:40