Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ormlite select count(*) as typeCount group by type

Tags:

ormlite

I want to do something like this in OrmLite

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

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

like image 741
shantur Avatar asked Nov 10 '22 09:11

shantur


1 Answers

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... 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.

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

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

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.

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 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
like image 145
user1445967 Avatar answered Jan 04 '23 03:01

user1445967