简体   繁体   中英

Unknown column in 'having clause'

I need to find in sakila database the longest rental period of a movie. I have tried 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM