SQL MAX-MIN in ORMLITE - ANDROID

2019-05-26 20:47发布

问题:

I want to know how can i use MAX MIN command with ORMLITE.

For example lets say we have this table

Table Name = Example
Column 1 = id
Column 2 = name

In ORMLITE how can i get max id ? I looked here but i didnt't understand exactly..

Can someone show me example about Max min in ORMLITE ?

回答1:

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();

I found this from documentation



回答2:

This is how I query for max ID in my code:

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();

A couple of alternative answers can also be found here: ORMLite - return item w/ maximum ID (or value)



回答3:

You can use:

dao.queryRawValue("select MAX(columnName) from tableName")

It will directly return long value.

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

queryRawValue(String query, String... arguments)

Perform a raw query that returns a single value (usually an aggregate function like MAX or COUNT). If the query does not return a single long value then it will throw a SQLException.