Using ORMLite, I want to count the number of database items that fit certain criteria. A simplified version of my database is as follows:
Employee Table:
employeeId
departmentId
Department Table:
departmentId
Salary Table:
employeeId
payGrade
Suppose I want to count the number of employees from a subset of departments that are at certain pay grade. When I try something like the following, I get an exception reporting that only one select column is allowed.
salaryQB.selectColumns(salaryQB.EMPLOYEE_ID);
salaryQB.where().eq(salaryQB.PAY_GRADE, 12);
employeeQB.where.in(Employee.DEPARTMENT_ID, departmentList)
.and().in(employeeQB.EMPLOYEE_ID, salaryQB);
employeeQB.setCountOf(true);
count = dao.countOf(employeeQB.prepare());
But code like this returns the following error:
RuntimeException (java.sql.SQLException: Inner query must have only 1
select column specified instead of 2)
Is there any way to do this short of writing a raw SQL query?
Hrm. I can’t see any problems with your code @Jeff. I’ve improved the exception message in ORMLite to show the actual field names for the future but that won’t help you right now:
The message is [obviously] trying to tell you that you have specified more than one
selectColumns(...)in thesalaryQBinnerQueryBuilder. But you seem to be only selecting one column here:I don’t see where the
salaryQBis defined but maybe there is some more code somewhere else that also is usingselectColumns? I’ve tried to reproduce the error in thetestInnerCountOf()method towards the bottom of theQueryBuilderTestunit test but it seems to work fine.If you can reproduce this in a unit test or if you can see how my unit test differs from your config then let me know.
Edit:
As of version 4.22 (from 9/2012), ORMLite now supports simple JOIN statements. So your query can be simplified to: