SQL MAX-MIN in ORMLITE - ANDROID

2019-05-26 20:28发布

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 ?

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-05-26 20:44

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楼-- · 2019-05-26 20:57

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-05-26 21:04
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

查看更多
登录 后发表回答