33

Employee 表有 ID 和 NAME 列。名称可以重复。我想知道是否至少有一行名称为“kaushik%”。

所以查询应该返回真/假或 1/0。

是否可以使用单个查询找到它。如果我们尝试类似

select count(1) from employee where name like 'kaushik%'

在这种情况下,它不返回真/假。此外,我们正在遍历表中的所有记录。有没有办法在简单的 SQL 中,每当获取满足条件的第一条记录时,它应该停止检查进一步的记录。或者这样的事情只能在 Pl/SQL 块中处理?

编辑 * Justin 提供的第一种方法看起来是正确的答案

SELECT COUNT(*) FROM employee WHERE name like 'kaushik%' AND rownum = 1
4

4 回答 4

40

通常,您会将其表达为

SELECT COUNT(*)
  FROM employee
 WHERE name like 'kaushik%'
   AND rownum = 1

谓词允许 Oracle在rownum = 1找到第一个匹配行后立即停止查找,或者

SELECT 1
  FROM dual
 WHERE EXISTS( SELECT 1
                 FROM employee
                WHERE name like 'kaushik%' )

whereEXISTS子句允许 Oracle 在找到第一个匹配行后立即停止查找。

第一种方法更紧凑,但在我看来,第二种方法更清晰一些,因为您确实是在寻找特定行是否存在而不是试图计算某些东西。但是第一种方法也很容易理解。

于 2013-01-28T16:55:35.500 回答
8

怎么样:

select max(case when name like 'kraushik%' then 1 else 0 end)
from employee

或者,什么可能更有效,因为like可以使用索引:

select count(x)
from (select 1 as x
      from employee
      where name like 'kraushik%'
     ) t
where rownum = 1
于 2013-01-28T16:50:16.187 回答
3

由于您要求 sql 查询应返回 1 或 0,因此您可以尝试以下查询:-

select count(1) from dual 
where exists(SELECT 1 
             FROM employee
             WHERE name like 'kaushik%')

Since the above query uses Exists, then it will scan the employee table and as soon as it encounters the first record where name matches "kaushik", it will return 1 (without scanning the rest of the table). If none of the records match, then it will return 0.

于 2013-01-28T17:07:50.467 回答
0
select 1 
 where exists ( select name 
                  from employee 
                  where name like 'kaushik%'
               )
于 2013-01-28T16:52:24.237 回答