选择存在与计数

问题描述

我正在使用sqlite-net-pcl。我需要哪个查询更好用。 我正在一张表中搜索是否至少有一条记录。

一个查询

Select exists(Select 1 from invnentory where itemname='Box2')

第二个查询

Select count(*) from inventory where itemname='Box2'

两个查询都正常运行。但是,使用sqlite-net-pcl最好的方法是什么?

解决方法

此查询:

Select count(*) from inventory where itemname = 'box2'

通常必须进行全表扫描以返回满足WHERE子句中条件的行数。

但这是

Select exists(Select 1 from invnentory where itemname='box2')

只要找到满足条件的第一行,就会立即返回,并且只有在没有第一行的情况下才会进行全表扫描。

因此EXISTS的效果应该更好。