CQL 使用简介——使用 SQL 查询数据

2014-09-26

本周我们正式推出了 Cloud Query Language,可以使用类似 SQL 的语法来查询 AVOS Cloud 平台上的应用数据。

一个简单的例子,比如在 iOS 里,如果您使用最新的 v2.6.5 版本 SDK,就可以像下面这个例子那样来查询:

NSString *cql = [NSString stringWithFormat:@"select * from %@", @"GameScore"];
    AVCloudQueryResult *result = [AVQuery doCloudQueryWithCQL:cql];
    NSLog(@"results:%@", result.results);

CQL 是目前只能用于查询数据,设计成类似 SQL 的语法,以下都是合法的 CQL 语句:

//查询一张表的最多 100 条数据
select * from GameScore

//查询表的记录总数
select count(*) from GameScore

//查询结果只包含 name,score 以及内置字段(objectId,createdAt等)
select name,score from GameScore

//根据 name 查找
select * from GameScore where name='dennis'

//根据 name 和 score 同时查找
select * from GameScore where name is exists and score > 80 and score <= 100

//分页查找,从第 100 条开始向后查找 10 条数据
select * from GameScore limit 100,10

//根据 score 和 name 排序
select * from GameScore order by score,+name desc

还可以查询符合条件的记录数目:

select count(*) from GameScore where score>60 and score<=80

我们还支持子查询,比如查询玩家信息,并且成绩大于 80 分的::

select * from Player where name in (select name from GameScore where score>80)

我们还可以通过 CQL 查询地理位置信息:

select * from Player where location near [30.0, -20.0]

更多复杂查询的例子请参考 Cloud Query Language 详细指南

Android SDK v2.6.5 版本 SDK 也开始支持,简单例子如下:

AVQuery.doCloudQueryInBackground("select * from ObjectTest",new CloudQueryCallback<AVCloudQueryResult>(){

          @Override
          public void done(AVCloudQueryResult result, AVException cqlException) {
             if(cqlException==null){
             result.getResults();//这里是你查询到的结果
             }
          }

});

数据来源

本文原载于 LeanCloud 团队博客,原地址 https://leancloudblog.com/cql-shi-yong-jian-jie-----shi-yong-sql-cha-xun-shu-ju/,取自 网站归档 中的 blog.leancloud.cn 副本,抓取日期 2026-07-27

正文按原样保留,图片换成本站保存的副本。指向本站已存档内容的链接改为站内地址,已经失效的链接改为互联网档案馆的快照,链接前的图标标明它现在通向哪里。原博客没有分类,标题上方的分类和产品由本站判定。