i need to find in sakila data base the longest rental period of a movie. i have trie this:
SELECT DISTINCT
customer.first_name
FROM
rental,
customer
WHERE
rental.customer_id = customer.customer_id
GROUP BY
rental.rental_id
HAVING
(
rental.return_date - rental.rental_date
) =(
SELECT
MAX(countRental)
FROM
(
SELECT
(
rental.return_date - rental.rental_date
) AS countRental
FROM
rental,
customer
GROUP BY
rental.rental_id
) AS t1
)
but i am getting the error:
1054 - Unknown column 'rental.return_date' in 'having clause'
does anybody know why? i have used a column that's supposed to be the aggregated data.. what am i missing
As written in the documentation
The SQL standard requires that HAVING must reference only columns in the GROUP BY clause or columns used in aggregate functions. However, MySQL supports an extension to this behavior, and permits HAVING to refer to columns in the SELECT list and columns in outer subqueries as well.
You have to specify return_date and rental_date in the select clause.
There are two options:
SELECT DISTINCT
customer.first_name,
rental.return_date,
rental.rental_date
FROM
rental,
customer
WHERE
rental.customer_id = customer.customer_id
GROUP BY
rental.rental_id
HAVING
(
rental.return_date - rental.rental_date
) =(
...
or
SELECT DISTINCT
customer.first_name,
(rental.return_date - rental.rental_date) as rental_duration
FROM
rental,
customer
WHERE
rental.customer_id = customer.customer_id
GROUP BY
rental.rental_id
HAVING
rental_duration =(
...
Both should work just fine.
来源:https://stackoverflow.com/questions/36105812/unknown-column-in-having-clause