您可以使用语句的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;