问题是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
)
答案 0 :(得分: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
答案 1 :(得分:0)
无论何时编写子查询,首先评估内部查询,然后评估外部查询。在第二个查询中,您使用的是实际上不存在的别名“a”。这就是您将收到错误的原因第二个查询,你不能使用它。第一个查询在语法上是正确的。