SELECT several rows WHERE satisfying two conditions

This would be better shown in my example:

I have a table where user responses from one large form are stored. There are 139 questions in each form. These questions are stored in different tables, connected, if necessary, with the question. Each user has an identifier. Now I need to make filters to show only those users that correspond to one or more answers on specific questions.

For example, I want users with question 14 to say yes, question 54 is not empty, and question 100 is greater than 10. Here's what the table looks like:

**userID** | **questionID** | **answer** 1 14 "yes" 1 54 "something" 1 100 "9" 2 14 "no" 2 54 "north 2 100 "50" 3 14 "yes" 3 54 "test" 3 100 "12" 

As a result, I want to return only userID 3, because it meets all the conditions.

It would be easy to contact ColdFusion, since it allows you to query in the requested results, but in PHP I did not find any way. It is important to have a chance to add a random number of questions, and not just three, as in this example.

+6
source share
3 answers

Try

 SELECT userID FROM tableName WHERE (questionID = 14 AND answer = 'yes' ) OR (questionID = 54 AND answer <> 'empty') OR (questionid = 100 AND answer > 10) GROUP BY userID HAVING COUNT(*) = 3 

SQLFiddle Demo

+7
source
 SELECT q.userID FROM questions q JOIN questions qq ON qq.userID=q.userID AND qq.questionID='54' AND qq.answer IS NOT NULL JOIN questions qqq ON qqq.userID=q.userID AND qqq.questionID='100' AND qqq.answer > 10 WHERE q.questionID=14 AND q.answer = 'yes' 
+4
source

You may try:

 SELECT questionID, answer FROM table WHERE ( questionID = 14 AND answer = 'yes' ) OR ( questionID = 54 AND answer != '' ) OR ( questionID = 100 AND answer > 10 ); 
+1
source

Source: https://habr.com/ru/post/925903/


All Articles