0

这是问题是sqlzoo,我写了以下代码,但我觉得它太多余了

SELECT year, freq 
FROM (SELECT yr AS year,count(title) AS freq
FROM movie, actor, casting
WHERE name= 'John Travolta'
AND movie.id=movieid
AND actor.id=actorid
GROUP BY yr) AS a
WHERE freq=(
SELECT MAX(freq)
FROM (SELECT yr AS year,count(title) AS freq
FROM movie, actor, casting
WHERE name= 'John Travolta'
AND movie.id=movieid
AND actor.id=actorid
GROUP BY yr) AS b
)

为什么不能这样?

SELECT year, freq 
FROM (SELECT yr AS year,count(title) AS freq
FROM movie, actor, casting
WHERE name= 'John Travolta'
AND movie.id=movieid
AND actor.id=actorid
GROUP BY yr) AS a
WHERE freq=(
SELECT MAX(freq)
FROM a
)
4

2 回答 2

1

在这种情况下,使用 CTE(通用表表达式)可能会有所帮助。这是您可以重用子查询的唯一方法。看看如何使用ROW_NUMBER来找到最大频率。我还将旧学校更新为FROM A, B, C WHERE ...新学校FROM A INNER JOIN B ...(虽然我不能 100% 确定 JOIN 标准是否正确。)

WITH a AS
(
    SELECT 
        yr AS year, 
        COUNT(title) AS freq
    FROM 
        movie
    INNER JOIN 
        casting ON movie.id = casting.movieid
    INNER JOIN 
        actor ON actor.id = casting.actorid
    WHERE 
        name = 'John Travolta'
    GROUP BY 
        yr),
b AS
(
     SELECT 
         year, freq,
         ROW_NUMBER() OVER (ORDER BY freq DESC) as RowNum
     FROM a
)
SELECT year, freq 
FROM  b
WHERE RowNum = 1
于 2012-04-08T19:26:00.197 回答
0

每当您编写子查询时,首先评估内部查询,然后评估外部查询。在您的第二个查询中,您使用的别名“a”实际上并不存在。这就是您在第二个查询中会出错的原因你不能使用它。第一个查询在语法上是正确的。

于 2012-04-08T17:47:12.303 回答