Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql select when matching multiple rows

Tags:

mysql

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.

like image 420
user1735943 Avatar asked May 04 '26 09:05

user1735943


2 Answers

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') 
like image 155
Anup Yadav Avatar answered May 05 '26 22:05

Anup Yadav


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)
like image 31
Crystal Avatar answered May 05 '26 22:05

Crystal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!