【问题标题】:Most efficient way to check if database contains any row? [duplicate]检查数据库是否包含任何行的最有效方法? [复制]
【发布时间】:2020-10-31 06:15:02
【问题描述】:

我有一个应用程序每 60 秒使用以下查询轮询数据库;

 SELECT TOP (1) id FROM item WHERE status = 5

我想知道是否有更有效的方法来检查我的表是否包含任何行?我这里不需要返回值,我只需要检查表是否包含任何具有该状态的行。

【问题讨论】:

  • 在没有order by 的情况下使用top 有点奇怪,最好通过使用exists 来避免整个问题,如GMB 的回答。 status 上有索引吗?
  • 不,恐怕没有索引。

标签: sql sql-server tsql count where-clause


【解决方案1】:

我会使用exists:

select case when exists (select 1 from item where status = 5) 
    then 1 
    else 0 
end as has_status_5

【讨论】:

  • 试过这个,它似乎工作,虽然它没有那么快。我的查询的执行时间是 00:00:00.044。有了这个 00:00:00.041。
猜你喜欢
  • 2016-10-19
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 2018-01-28
  • 2020-03-23
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
相关资源
最近更新 更多