使用Sqlite优化查询时的情况

时间:2015-01-19 10:29:40

标签: sql database sqlite

我有三个表ABC。我必须检测它们中是否有任何行。只要检测到任何具有零行的表,我就不需要检查其他表。

所以,一种方法是我分别执行三个查询,并在每次查询后检查返回的行数。如果它非零,则只执行下一个表的查询。

第二种方法是使用case-when编写单个查询,类似

select case 
when (select count(*) from A = 0)
then 1
else (
      select case 
      when (select count(*) from B = 0)
      then 1 
      else (
           select case
           when (select count(*) from B = 0)
           then 1
           else 0
           )
      )
end as matchResult; 

第二种方法需要较少的代码,因为我必须编写一个查询,db会为我做比较。

我的问题是它是否过度使用或我是否可以进一步优化查询?

修改

在进一步研究中,我意识到上面的查询是错误的。但是,我可以简单地将其作为

select case 
when (select count(*) from A) = 0 and
     (select count(*) from B) = 0 and
     (select count(*) from C) = 0  
then 1
else 0
end as matchResult;

如果我没有错,则从左到右检查and条件,如果任何一个为假,则不检查右边的条件。

请确认这一点。

2 个答案:

答案 0 :(得分:1)

计数有点贵

select 1  
where not exits (select * from a) 
   or not exits (select * from b) 
   or not exits (select * from c)

答案 1 :(得分:-2)

一个包含三个结果的查询:

select (select count(*) from A) as Acount, 
       (select count(*) from B) as Bcount, 
       (select count(*) from C) as Ccount

这改为给出最合适的表的名称为空:

select case
   when (select count(*) from A)=0 then 'A' 
   when (select count(*) from B)=0 then 'B'
   when (select count(*) from C)=0 then 'C'
   else 'ops, all have records'             -- remove this to have a null
end as first_empty_table