mik*_*ike 17 mysql sql database 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
)
Run Code Online (Sandbox Code Playgroud)
但我收到错误:
有谁知道为什么?我使用了一个应该是聚合数据的列..我缺少什么
pio*_*jow 32
如文档中所述
SQL标准要求HAVING必须仅引用GROUP BY子句中的列或聚合函数中使用的列.但是,MySQL支持对此行为的扩展,并允许HAVING引用SELECT列表中的列和外部子查询中的列.
您必须在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
) =(
...
Run Code Online (Sandbox Code Playgroud)
要么
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 =(
...
Run Code Online (Sandbox Code Playgroud)
两者都应该工作得很好.
| 归档时间: |
|
| 查看次数: |
19115 次 |
| 最近记录: |