我目前正在完成sqlzoo的More JOIN operations教程,并遇到以下代码作为#12的答案:
SELECT yr,COUNT(title)
FROM movie
JOIN casting
JOIN actor
ON actorid=actor.id AND movie.id=movieid
WHERE name='John Travolta'
GROUP BY yr
HAVING COUNT(title)=
(SELECT MAX(c) FROM
(SELECT yr, COUNT(title) AS c
FROM movie
JOIN casting ON movie.id=movieid
JOIN actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr) AS t
)
是否有更简洁的方式来表达此代码?
答案 0 :(得分:2)
是。如果我正确理解问题,那就更简单了。
SELECT yr,COUNT(title)
FROM movie JOIN casting ON movie.id=movieid
JOIN
actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr
HAVING COUNT(title) > 2
答案 1 :(得分:1)
看起来原始网站的建议答案与他们提出的问题不符。
他们问的最佳答案:
SELECT yr,COUNT(title) FROM
movie JOIN casting ON movie.id=movieid
JOIN actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr
HAVING COUNT(title)>2
他们的回答是:
SELECT yr,COUNT(title) FROM
movie JOIN casting ON movie.id=movieid
JOIN actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr
HAVING COUNT(title)=
(SELECT MAX(c) FROM (SELECT yr,COUNT(title) AS c
FROM movie
JOIN casting ON movie.id=movieid JOIN actor ON actorid=actor.id
WHERE name='John Travolta'
GROUP BY yr) AS t
)
但这实际上回答了一个不同的问题,即:“他制作电影的时间最多,那年是哪一年,他制作了多少部电影?”