2013-09-27 80 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。

相關問題