7

如果只有一行存在,我需要选择一行,如果有更多行,它应该选择 0 行。

4

7 回答 7

7

如果您使用的是 PL/SQL,那么如果返回多于一行,则选择使用的列select-into将引发异常:too_many_rows

declare
  var table.column%type;
begin
  select column
  into   var
  from   table
  where  ...;
end;

如果您只想使用 SQL 来执行此操作,那么您可以执行以下操作:

select *
from
  (select s.*, count(*) over () c
   from
    (select *
     from table
     where ...
     and   rownum <= 2
    ) s
)
where c = 1

更新

正如 DazzaL 在评论中所说,rownum <= 2限制的原因是如果结果集中有超过 2 行,则将查询短路。如果数据集很大,这可以带来显着的性能优势。

于 2013-04-02T10:08:38.923 回答
2

我想出了这个,只是为了它,使用 CTE

With counter as
( select count(any_field) as cnt from your_query
)
SELECT
  your_query
WHERE exists (SELECT cnt from Counter WHERE cnt=1)

有 1 条记录时为 1 行 - http://sqlfiddle.com/#!4/84c7b/2
超过 1 条记录时为 0 行 - http://sqlfiddle.com/#!4/95c4a/1

编辑
或者如果你想避免重复整个查询......一个例子:(
使用来自 sqlfiddle http://sqlfiddle.com/#!4/6a2d8/117的模式)

With results as
( select * from montly_sales_totals
),
counter as
( SELECT count(name) as cnt FROM results
)
SELECT *
FROM results
WHERE exists (SELECT cnt from Counter WHERE cnt=5)
于 2013-04-02T10:29:57.553 回答
1
SELECT fld1, fld2
FROM (SELECT COUNT(*) over() cnt ,fld1, fld2 FROM tbl WHERE fld1 = 'key')
WHERE cnt = 1
于 2013-04-02T10:34:53.527 回答
0

如果只有一行存在,我需要选择一行,如果有更多行,它应该选择 0 行。

我假设该表仅包含您有兴趣查看(或不查看)的行,在这种情况下,我会写类似

select *
  from table1
 where 1 = (select count(1) 
              from table1
           )

如果您只想从表的结果子集中查看一行,我会选择类似的内容:

with t as ( select *
              from table1
             where [put here your condition]
)
select *
  from t
 where 1 = (select count(1) 
              from t
           )
于 2013-04-02T14:15:38.990 回答
0

试试这个:

SELECT f1,f2
FROM  Table
WHERE (f1 = @f1) AND (f2=@f2) AND (f3=@f3)
GROUP BY f1,f2
HAVING (COUNT(*) = 1)
于 2017-01-07T11:43:53.507 回答
-1

试试这个:

SELECT col1, col2 FROM
(SELECT count(id) as 'cnt', col1, col2 FROM table_name WHERE col1='value') 
WHERE cnt=1;
于 2013-04-02T10:06:01.810 回答
-1

声明 COL_COUNT NUMBER;
BEGIN
COL_COUNT: = 0 ;
SELECT COUNT (1) INTO COL_COUNT FROM USER_TAB_COLUMNS WHERE TABLE_NAME = '(你的表名)';
IF COL_COUNT = 0 THEN
EXECUTE IMMEDIATE ('select * from dual') ;
万一;
结尾;

于 2013-04-02T10:08:54.463 回答