'having clause' 中的未知列

Unknown column in 'having clause'

我需要在 sakila 数据库中查找电影的最长租期。 我试过这个:

  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
    )

但我收到错误消息:

# 1054 - Unknown column 'rental.return_date' in 'having clause'

有人知道为什么吗?我使用了一个应该是聚合数据的列。我错过了什么?

如文档中所写

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.

您必须在 select 子句中指定 return_date 和 rental_date。

有两种选择:

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
  ) =(
  ...

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 =(
  ...

两者应该都能正常工作。