如何强制查询只返回一条记录?

时间:2017-11-30 19:16:24

标签: sql sql-server tsql

我收到以下错误:

  

'子查询返回的值超过1。这是不允许的   子查询跟随=,!=,...

这是我的疑问:

SELECT TOP 1

我试过了:

let getLinkTopicsSql = "SELECT TOP 1 Topic.Id, 
                                     Topic.Name, 
                                     isnull( (select 1 from FeaturedTopic where TopicId = Topic.Id),0) as IsFeatured 

                        FROM         Topic
                        INNER JOIN   LinkTopic
                                        ON   LinkTopic.TopicId = Topic.Id
                        INNER JOIN   Link
                                        ON   LinkTopic.LinkId =  Link.Id
                        WHERE        Link.Id = @LinkId"

像这样:

a = {'making' : 1, 'jumping' : 2, 'climbing' : 1, 'running' : 2}
b = {ps.stem(w) : a[w] for w in a.keys()}
print(b)
>>> {'climb': 1, 'jump': 2, 'make': 1, 'run': 2} #output

但我仍然收到同样的例外。

我不确定如何解决这个问题......

1 个答案:

答案 0 :(得分:3)

我想你想要exists

(case when exists (select 1 from FeaturedTopic where TopicId = Topic.Id)
      then 1 else 0
 end) as IsFeatured 

您可以使用isnull()执行此操作,如:

isnull( (select top (1) 1 from FeaturedTopic where TopicId = Topic.Id), 0) as IsFeatured 

或没有:

select coalesce(max(1), 0) from FeaturedTopic where TopicId = Topic.Id) as IsFeatured 

但我认为exists是最清晰的形式。