2

我有一个非常独特的需要让 select 总是返回一行

我的 SQL:

select * from table1 Where (table1.pk = :p1) or (table1.fk1 = :p1)

上面的 SQL 总是有两种返回的情况:

1-我的选择返回两条记录:唯一不同的是一条记录有数据,而另一条记录只有填充数据的ID,而其余字段为空。在这种情况下,我只需要返回在其他字段中有数据的那个。

2-我的选择返回一条记录在这种情况下,返回的记录只有ID字段填充了数据,而其余字段为空,但这是我想要的,不需要任何进一步的处理。

请告知是否可以在一个普通的 Select SQL 中做到这一点。我不能使用存储过程。

4

1 回答 1

3

您可以使用语句的first子句select仅获取 1 行。

鉴于您的特定条件,您可以按其余字段降序排列结果集,以确保仅在没有数据行的情况下选择空行(null 在 firebird 2.5 中首先出现,但 AFAIK 这在最后一个版本中发生了变化,因此在应用此之前请检查您的特定版本)。

您的最终查询将如下所示:

select first 1 * 
  from table1 
 where (table1.pk = :p1) 
    or (table1.fk1 = :p1)
 order by somecolumn;

somecolumn是可以包含空值的其他字段中最相关的。

您可以使用以下语句对此进行测试:

--two rows, one with ID and values and the other with ID and null
with q1 as (
      select 1 id, 'data' othercolumn
        from rdb$database
      union
      select 2 id, null othercolumn
        from rdb$database
     ) 
select first 1 *
  from q1
 order by othercolumn nulls last;

--versus:

--onw row with ID and null
with q1 as (
      select 2 id, null othercolumn
        from rdb$database
     ) 
select first 1 *
  from q1
 order by othercolumn nulls last;
于 2013-01-22T04:08:27.633 回答