2013-09-27 79 views
2

我想知道如何将MAX MIN命令与ORMLITE一起使用。ORMLITE中的SQL MAX-MIN - ANDROID

例如让我们说我们有这个表

表名称=实例
列1 = ID
列2 =名称

在ORMLITE我怎样才能获得最大的ID?我看着here但我didnt't准确理解..

能有人告诉我如约最大值最小值在ORMLITE?

回答

9
QueryBuilder<Account, Integer> qb = accountDao.queryBuilder(); 

qb.selectRaw("MIN(orderCount)", "MAX(orderCount)"); 

// the results will contain 2 string values for the min and max 

results = accountDao.queryRaw(qb.prepareStatementString()); 

String[] values = results.getFirstResult(); 

我发现这个从documentation

4

这是我在我的代码查询最多ID:

QueryBuilder<Example, String> builder = dao.queryBuilder(); 
builder.orderBy("id", false); // true or false for ascending so change to true to get min id 
Example example = dao.queryForFirst(builder.prepare()); 
String id = null; 
if (example == null) 
    id = "-1"; 
else 
    id = example.getId(); 

几个备选答案也可以在这里找到: ORMLite - return item w/ maximum ID (or value)

+1

+1您还应该添加一个'limit(1)',因为只会返回一个结果。 – Gray

+0

@Gray - 只有一点:在较新版本的ORMLite中,限制(int)已被弃用。你必须使用限制(1L)。但是,感谢你们两位! – bernhardrusch

0

您可以使用:

dao.quer yRawValue(“select MAX(columnName)from tableName”)

它将直接返回long值。

参考:http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_5.html#DAO-Methods

queryRawValue(查询字符串,字符串...参数)

执行返回单个值(通常是一个聚集函数像MAX或COUNT)原始查询。如果查询没有返回单个长整型值,则会抛出一个SQLException。

相关问题