简体   繁体   English

SQL中的COUNT与SELECT

[英]COUNT vs SELECT in SQL

What is better approach to check existence of an object in database? 什么是检查数据库中对象是否存在的更好方法?

select count(id) as count from my_table where name="searchedName";

OR 要么

select id from my_table where name="searchedName";

And then check if count > 0 or the object is not null (ORM logic) 然后检查count > 0或对象是否不为空(ORM逻辑)

EDIT: 编辑:

select id to be valid for Oracle. select id对Oracle有效。

The idea should be to that we only need to find one record in order to say that such record exists. 想法应该是我们只需要找到一条记录就可以说该记录存在。 This can be done with an EXISTS clause in standard SQL. 这可以通过标准SQL中的EXISTS子句完成。

select exists (select * from mytable where name = 'searchedName');

returns true if the table contains a record with 'searchedName' and false otherwise. 如果表包含带有“ searchedName”的记录,则返回true,否则返回false。

If you want 0 for false and 1 for true instead (eg if the DBMS does not support booleans): 如果您希望0表示false,而1表示true(例如,DBMS不支持布尔值):

select case when exists (select * from mytable where name = 'searchedName') 
  then 1 else 0 end as does_exist;

You say you want this for Oracle. 您说您想要Oracle的产品。 In Oracle you can use above query, but you'd have to select from the table dual : 在Oracle中,您可以使用上面的查询,但是您必须从表dual进行选择:

select case when exists (select * from mytable where name = 'searchedName') 
  then 1 else 0 end as does_exist
from dual;

But for Oracle we'd usually use rownum instead: 但是对于Oracle,我们通常使用rownum代替:

select count(*) as does_exist
from mytable 
where name = 'searchedName'
and rownum = 1; -- to find one record suffices and we'd stop then

This also returns 1 if the table contains a record with 'searchedName' and 0 otherwise. 如果表包含带有“ searchedName”的记录,则此方法还返回1,否则返回0。 This is a very typical way in Oracle to limit lookups and the query is very readable (in my opinion). 这是Oracle中限制查询的一种非常典型的方法,并且查询非常易读(我认为)。

I'd just call: 我只是打电话给:

select id from my_table where name='searchedName';

Making sure there is an index for the name column. 确保name列有索引。 And then check whether or not the result is empty. 然后检查结果是否为空。

Try with IF EXISTS ( 尝试使用IF EXISTS(

if exists (select 1 from my_table where name = "searchedName")
begin
     ....
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM