Reputation: 28188
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?
Upvotes: 0
Views: 686
Reputation: 116908
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:
Inner query must have only 1 select column specified instead of 2: [id, foreign]
The message is [obviously] trying to tell you that you have specified more than one selectColumns(...)
in the salaryQB
inner QueryBuilder
. But you seem to be only selecting one column here:
salaryQB.selectColumns(salaryQB.EMPLOYEE_ID);
I don't see where the salaryQB
is defined but maybe there is some more code somewhere else that also is using selectColumns
? I've tried to reproduce the error in the testInnerCountOf()
method towards the bottom of the QueryBuilderTest
unit 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:
salaryQB.where().eq(salaryQB.PAY_GRADE, 12);
employeeQB.join(salaryQB);
employeeQB.where().in(Employee.DEPARTMENT_ID, departmentList);
employeeQB.setCountOf(true);
count = dao.countOf(employeeQB.prepare());
Upvotes: 2