【问题标题】:Select single row in SQL Server with a condition that selects more than one row在 SQL Server 中选择单行,条件是选择多行
【发布时间】:2015-12-01 07:01:38
【问题描述】:

我要从中选择数据的表:

代码:

if exists(select * from MyTable where ActChildID_FK = @actid_fk)    
begin    
    declare @parentid int, @fnname nvarchar(100)    

    select @parentid = ActParentID_FK 
    from MYTabe 
    where ActChildID_FK = @actid_fk    
end

问题是当ActChildID_FK = 300734 返回ActParentID_FK 的2 个值时,我只需要能够接收一个值并且我不想更改表中的任何值。

【问题讨论】:

  • 我只需要能够接收一个值 ...哪一个值?

标签: sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2


【解决方案1】:

只需使用TOP 1 获取单行。查看这篇文章的更多细节:https://msdn.microsoft.com/en-us/library/ms189463.aspx

if exists(select * from MyTable where ActChildID_FK = @actid_fk)

begin    
     declare @parentid int,@fnname nvarchar(100)    
     select TOP 1 @parentid = ActParentID_FK from MYTabe where ActChildID_FK = @actid_fk    
end

【讨论】:

  • 实际上,如果只有 300734 和 300735,我希望语句检查另一个表,然后我希望父 ID 为 300678,但如果有 300734 和 300735 和 300140, 300141 ...等然后父 ID 应该是 300138 。这就是问题
【解决方案2】:

是否有任何条件可以从您获得的 2 个结果中只取 1 个。如果没有,您可以简单地使用“Top 1”

if exists(select * from MyTable where ActChildID_FK = @actid_fk)

begin

declare @parentid int,@fnname nvarchar(100)

select top 1 @parentid = ActParentID_FK from MYTabe where ActChildID_FK = @actid_fk

END

【讨论】:

  • 实际上,如果只有 300734 和 300735,我希望语句检查另一个表,然后我希望父 ID 为 300678,但如果有 300734 和 300735 和 300140, 300141 ...等然后父 ID 应该是 300138 。这就是问题
  • 你是说它是基于父母拥有的孩子的数量吗?计数更高的父母?
  • @Harvester -- 不清楚选择值的规则是什么 -- 你能否在在你的问题中给出实际输入和预期结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 2021-11-22
相关资源
最近更新 更多