query with multiple IN parameters
Hello all,
A beginner in Java although have couple of years using Stata(statistical software) and its odbc. I will run a query which asks users to input user_id.
select distinct doc_id from documents where user_id=b. The user has to input b. Based on that, the query will generate some integers like this
doc_id
2
3
4
Next I need to transform the column values horizontally separated by comma. In Stata, I would do something called levelsof. So, I have now
2,3,4
I need to take 2,3,4 and put it in my next final query like this..
select count(*) from readership where source_id in (2,3,4)
Can this be done in Java?? Any help will be highly appreciated...
Thanks..
Re: query with multiple IN parameters
This is purely a SQL query, not a Java thing.
A single one at that.
Code:
SELECT count(*)
FROM readership
WHERE source_id IN
(SELECT distinct doc_id etc etc)
This assumes you don't need the intermediate step.
Re: query with multiple IN parameters
Thanks.. but unfortunately each query has to be performed on different database. So, basically I need to get the distinct doc_id from one database and use that to get counts from another database. Well, basically what I am looking for is the way to do using JDBC api. I see that you could do this if I wanted a placeholder for each IN parameter, I could use ("?").
select count(*) from readership where source_id=?
psmt.setLong(1,1234)
My question is what is the method if I need a placeholder for multiple integers like
select count(*) from readership where source_id in (1,2,3,4,6) // not a single integer represented by "?" but bunch of integers separated by comma. Please let me know if you need more detail. Thanks.
Re: query with multiple IN parameters
Assuming the number of ids in the IN clause is fairly limited (Oracle, for example, has a limit of around 1000), then the usual technique is to either concatenate the IN clause (if they are likely to vary a lot), which makes each query unique, or to build the IN clause for a PreparedStatement something along the lines of:
Code:
for (each id) {
if (firstId) {
preparedStatementString.append("?");
} else {
preparedStatementString.append(",?");
}
}
then assign them:
Code:
for (each id) {
ps.setInt(<loopIndex>, id);
}
Note, of course, that the above is not copy/paste material.