正在使用' ANY'这里有必要(sql)

时间:2014-12-28 11:55:31

标签: sql

嘿,我是sql语言的新手 我有一个关系Movie(title, year, length, inColor, studioName, producerC#)

问题是(哪部电影比“乱世佳人”更长?)

我想知道这两个答案之间是否有区别,哪一个是正确的,为什么

select title 
from movie 
where length>any(select length from movie where title ='gone with the wind')

select title 
from movie 
where length>(select length from movie where title ='gone with the wind')

提前致谢

3 个答案:

答案 0 :(得分:3)

length > ANY (<select>)表示length需要高于select返回的值中的一个(或更多)。此选择可以返回多个值。只有当您知道select为单例选择(即它只生成一行)时才能用> (<select>)替换它。

答案 1 :(得分:1)

如果title ='gone with the wind'的长度更长,那么Any将帮助您查找子查询中任何一个长度更长的电影。

select title 
from movie 
where length>any(select length from movie where title ='gone with the wind')

只有当一个长度只有title ='gone with the wind'时,第二个查询才能解决,否则会抛出错误subquery returned more than one value。它将获取长度大于子查询结果的电影

select title 
from movie 
where length>(select length from movie where title ='gone with the wind')

如果您有超过一部电影的长度,请选择第一个查询,否则使用第二个查询。

答案 2 :(得分:1)

如果您知道标题是唯一的,请使用:

select title 
from movie 
where length > (select length from movie where title = 'gone with the wind');

使用any有点误导,因为它暗示可能有多个匹配。

如果有多个匹配,我会使用:

select title 
from movie 
where length > (select min(length) from movie where title = 'gone with the wind');

或:

where length > (select max(length) from movie where title = 'gone with the wind');

取决于我的意思。

就个人而言,当与子查询一起使用时,我发现关键字anysomeall没有任何用处。我认为使用聚合更容易理解生成的查询,这使得特定的比较显而易见。