3

I have a project where I need to select only the users that answered to some questions in a certain way (based on a filter).

The filter table (filter) looks like this

   question |   answer  

   Q1       |    A  
   Q2       |    B 

The user table (answers) looks like this

user | question | answer  

  1  |    Q1    |    A  
  1  |    Q2    |    D  
  2  |    Q1    |    A  
  2  |    Q2    |    B 

How can I select from the user table only the user(s) that match the filter?
I tried

"SELECT user FROM answers WHERE (question = Q1 AND answer = A) 
             AND (question = Q2 AND answer = B)" 

and it doesn't work -- I get an empty result. Thank you.

3 Answers 3

3

In your query you are asking to get data which is not present. You are trying to get that user which has both the combination.

Try this

SELECT user FROM answers WHERE (question = 'Q1' AND answer = 'A') 
         OR (question = 'Q2' AND answer = 'B') 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it is present. I need the user that answered A to Q1 and B to Q2, to match the filter. What you are proposing will look only for one question/answer pair and not for both.
2

try this

select answers.user
from filter, answers
where filter.question=answers.question and filter.answer=answers.answer
group by answers.user having count(answers.question)=2

or

select user
from answers
where user not in 
(select distinct a.user from answers a, filter f 
where a.question=f.question and a.answer!=f.answer)

1 Comment

Both your solutions work. Great job and thanks for taking the time. I have now to see which solution is the fastest.
2

Try this:

Select 
DISTINCT(userId)
from user_table ut
inner join filtertable ft on (ut.question=ft.question and ut.answer=ft.answer)

3 Comments

I was going to write almost the same query with the same join conditions, but the OP only wanted to select answer.user.
To do that he needs select distinct id
It doesn't work. I get both users and I should get only user 2, because only user 2 completely matches the filter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.