mySQL使用有效语法在子查询上给出语法错误

时间:2013-10-15 02:25:59

标签: mysql sql subquery

我正在努力寻找那些在没有使用限制的情况下租得最多的电影。我正在尝试使用以下查询:

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告诉我,我在SELECT COUNT(r2.rental_id) FROM rental r2, inventory某处有语法错误但是,当我独立运行子查询时,它会返回预期的表。我做了大错的事吗?

相关数据库架构:

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)

2 个答案:

答案 0 :(得分:1)

您不能在结果集上使用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);

答案 1 :(得分:0)

我没有要测试的数据库,但这应该可行:

编辑为LIMIT 1而不是SELECT TOP 1 for MySQL)

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) = (SELECT COUNT(r2.rental_id)
                              FROM rental r2, inventory i2
                              WHERE i2.inventory_id = r2.inventory_id
                              GROUP BY i2.film_id
                              ORDER BY COUNT(r2.rental_id) desc
                              LIMIT 1) s