I’m trying to execute the following SQL query in SQL Server 2008
String query = "SELECT SUM(r.rate),COUNT(q.best_answer_id) " +
"FROM questions_rating r,questions q " +
"WHERE r.question_id IN (SELECT question_id FROM questions WHERE user_id = 1) "+
"AND q.best_answer_id IN (SELECT answer_id FROM answers WHERE user_id = 1)";
These are the Tables
Questions_Rating
id---------question_id-----------user_id--------rate
1 1 1 1
2 1 2 1
3 1 3 -1
4 2 1 -1
The rate can only be either 1 or -1.
Questions
question_id------question-------user_id-------best_answer_id
1 lala 1 3
2 lala 2 5
Answers
answer_id---------answer--------user_id------question_id
1 lala 4 1
2 kaka 5 1
3 dada 6 1
4 fafa 7 2
5 tata 8 2
The query is returning these results
SUM------COUNT
NULL 0
While it should return…
SUM------COUNT
1 0
Note that the following query returns the right result (1)
String query = "SELECT SUM(r.rate) " +
"FROM questions_rating r " +
"WHERE r.question_id IN (SELECT question_id FROM questions WHERE user_id = 1) ";
I think you should consider rewriting your query to use
JOINSinstead of your subqueries:See SQL Fiddle with Demo
Returns the result: