Unknown column in 'having clause'

后端 未结 1 1543
抹茶落季
抹茶落季 2020-12-06 04:37

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,
         


        
相关标签:
1条回答
  • 2020-12-06 04:56

    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.

    0 讨论(0)
提交回复
热议问题