iOS 本地数据库查询之一条语句查询多个字段的count

1 、需求是一张表中有status(枚举)、state(枚举)、complete(bool)等多个字段,现在需要查询出 status = 2, state = 0, complete = yes的 count,这里只列举了这三个字段,其实还有很多要查的,本来想使用for循环

select count(status)from table where status = 1
iOS 本地数据库查询之一条语句查询多个字段的count_第1张图片
image.png

1.1、上图操作数据库表的工具是DB Browser for SQLite,可以自行下载,

1.2、 找到db存放的位置(一般是document下面,路径是app内部设置,取决于自己),双击.db即可打开DB Browser for SQLite软件

iOS 本地数据库查询之一条语句查询多个字段的count_第2张图片
image.png

1.3、如果需要查询的字段比较多的时候,使用for循环查出单条字段count显然比较慢,这时候可以整合成一个查询语句

"select * from (select count(0) from Instrument where status = 0 and isHidden = 0  And projectId = 50832),(select count(1) from Instrument where status = 1 and isHidden = 0  And projectId = 50832),(select count(2) from Instrument where status = 2 and isHidden = 0  And projectId = 50832),(select count(3) from Instrument where status = 3 and isHidden = 0  And projectId = 50832),(select count(4) from Instrument where missing = 1 and isHidden = 0  And projectId = 50832),(select count(5) from Instrument where review = 1 and isHidden = 0  And projectId = 50832),(select count(6) from Instrument where completed = 1 and isHidden = 0  And projectId = 50832),(select count(7) from Instrument where status in (1,2,3) And localCreatedTime = localLastUpdateTime and isHidden = 0 And projectId = 50832),(select count(8) from Instrument where status in (1,2,3) And localCreatedTime is null or localCreatedTime != localLastUpdateTime and isHidden = 0 And projectId = 50832),(select count(9) from Instrument where isHidden = 1 And status = 1  And projectId = 50832),(select count(10) from Instrument where needToBeRelocated = 1 and isHidden = 0  And projectId = 50832)"

iOS 本地数据库查询之一条语句查询多个字段的count_第3张图片
查询语句

1.4、 查询结果是swift语言下的打印,不是OC,count括号里面加上数字是为了标记每个count,以便于和查询对象对应起来

iOS 本地数据库查询之一条语句查询多个字段的count_第4张图片
查询结果

你可能感兴趣的:(iOS 本地数据库查询之一条语句查询多个字段的count)