简体   繁体   English

“具有条款”中的未知列

[英]Unknown column in 'having clause'

I need to find in sakila database the longest rental period of a movie.我需要在 sakila 数据库中找到电影的最长租期。 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. SQL 标准要求 HAVING 必须仅引用 GROUP BY 子句中的列或聚合函数中使用的列。 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.但是,MySQL 支持此行为的扩展,并允许 HAVING 引用 SELECT 列表中的列和外部子查询中的列。

You have to specify return_date and rental_date in the select clause.您必须在 select 子句中指定 return_date 和rental_date。

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.两者都应该工作得很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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