28

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?

Ondrej Slinták
  • 29,278
  • 20
  • 90
  • 124
mike
  • 607
  • 2
  • 10
  • 17

1 Answers1

50

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.

piotrgajow
  • 2,500
  • 1
  • 21
  • 23
  • thank you for answering. in which select clause ? i got 3. and i only want their minus operator result – mike Mar 19 '16 at 19:15
  • The topmost SELECT. I have updated the answer with two possibilities. – piotrgajow Mar 19 '16 at 19:21
  • only the first option worked, but i actually need the second one, because i need to show the duration. the second option gives the same error – mike Mar 19 '16 at 19:39
  • This second one should work also... Can you try again? (I have fixed one error just after the first edit, maybe you used query before corrections). Can you say what version of MySQL are you using? – piotrgajow Mar 19 '16 at 20:08
  • The mentioned MySQL extension is ONLY_FULL_GROUP_BY sql_mode. More info see https://dev.mysql.com/doc/refman/5.6/en/sql-mode.html#sqlmode_only_full_group_by – Jan May 11 '20 at 12:13