如果查询返回一行,如何选择记录,如果查询返回更多行,则选择无记录

时间:2013-04-02 09:57:36

标签: sql oracle

在oracle SQL中,如果只存在一行,我需要选择一行,如果有更多行,则应选择0行。

7 个答案:

答案 0 :(得分:5)

如果您正在使用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行,则会使查询短路。如果数据集很大,这可以带来显着的性能优势。

答案 1 :(得分: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 rec时的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)

答案 2 :(得分:1)

SELECT fld1, fld2
FROM (SELECT COUNT(*) over() cnt ,fld1, fld2 FROM tbl WHERE fld1 = 'key')
WHERE cnt = 1

答案 3 :(得分: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
           )

答案 4 :(得分:0)

试试这个:

SELECT f1,f2
FROM  Table
WHERE (f1 = @f1) AND (f2=@f2) AND (f3=@f3)
GROUP BY f1,f2
HAVING (COUNT(*) = 1)

答案 5 :(得分:-1)

试试这个:

SELECT col1, col2 FROM
(SELECT count(id) as 'cnt', col1, col2 FROM table_name WHERE col1='value') 
WHERE cnt=1;

答案 6 :(得分:-1)

DECLARE COL_COUNT NUMBER;
BEGIN
COL_COUNT:= 0;
SELECT COUNT(1)INTO COL_COUNT来自USER_TAB_COLUMNS WHERE TABLE_NAME ='(你的表名)';
如果COL_COUNT = 0那么 EXECUTE IMMEDIATE('select * from dual');
结束IF;
END;