ormlite select count(*) as typeCount 按类型分组 [英] ormlite select count(*) as typeCount group by type

查看:90
本文介绍了ormlite select count(*) as typeCount 按类型分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 OrmLite 中做这样的事情

I want to do something like this in OrmLite

SELECT *, COUNT(title) as titleCount from table1 group by title;

有没有什么方法可以通过 QueryBuilder 做到这一点而不需要 queryRaw?

Is there any way to do this via QueryBuilder without the need for queryRaw?

推荐答案

文档指出,使用 COUNT() 等需要使用 selectRaw().我希望有办法解决这个问题——不必将我的 SQL 写成字符串是我选择使用 ORMLite 的主要原因.

The documentation states that the use of COUNT() and the like necessitates the use of selectRaw(). I hoped for a way around this - not having to write my SQL as strings is the main reason I chose to use ORMLite.

http://ormlite.com/docs/query-builder

selectRaw(String...列):
添加原始列或聚合函数(COUNT, MAX, ...) 到查询.这将把查询变成只适合用作原始查询的东西.这可以称为多次添加更多要选择的列.请参阅发行原始部分查询.

selectRaw(String... columns):
Add raw columns or aggregate functions (COUNT, MAX, ...) to the query. This will turn the query into something only suitable for using as a raw query. This can be called multiple times to add more columns to select. See section Issuing Raw Queries.

关于使用 selectRaw() 的更多信息,因为我正在尝试同样的事情:

Further information on the use of selectRaw() as I was attempting much the same thing:

文档指出,如果您使用 selectRaw(),它将将查询转换为"应该由 queryRaw() 调用的查询.

Documentation states that if you use selectRaw() it will "turn the query into" one that is supposed to be called by queryRaw().

它没有解释的是,通常对 selectColumns()selectRaw() 的多次调用是有效的(如果您只使用其中一个),在 selectColumns() 之后使用 selectRaw() 有一个隐藏的"副作用,即清除您之前调用的任何 selectColumns().

What it does not explain is that normally while multiple calls to selectColumns() or selectRaw() are valid (if you exclusively use one or the other), use of selectRaw() after selectColumns() has a 'hidden' side-effect of wiping out any selectColumns() you called previously.

我相信 selectRaw() 的 ORMLite 文档会得到改进,注意它的使用不打算与 selectColumns() 混合使用.

I believe that the ORMLite documentation for selectRaw() would be improved by a note that its use is not intended to be mixed with selectColumns().

QueryBuilder<EmailMessage, String> qb = emailDao.queryBuilder();
qb.selectColumns("emailAddress"); // This column is not selected due to later use of selectRaw()!
qb.selectRaw("COUNT (emailAddress)");

ORMLite 的例子并不像我想要的那么丰富,所以这里有一个完整的例子:

ORMLite examples are not as plentiful as I'd like, so here is a complete example of something that works:

QueryBuilder<EmailMessage, String> qb = emailDao.queryBuilder();        
qb.selectRaw("emailAddress"); // This can also be done with a single call to selectRaw()
qb.selectRaw("COUNT (emailAddress)");
qb.groupBy("emailAddress");
GenericRawResults<String[]> rawResults = qb.queryRaw(); // Returns results with two columns

这篇关于ormlite select count(*) as typeCount 按类型分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆