Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql query on combination of AND and OR

Tags:

mysql

I want to write a MySql query whereby I want to use combination of AND and OR. I have 6 attributes where in I want one String to appear AND there is one attribute in which a compulsory thread should appear.

My command looks like this.

Select * from Students where roll_no like '__2011%' and subject1 ='maths' or subject2='maths' or subject3='maths' or subject4='maths' or subject5='maths' or subject6='maths';

I want 'maths' to appear in atleast one of those subject attributes. Along with that Roll no should have 2011 in it as specified in the query. Please help me.

like image 876
Prasad Avatar asked Oct 20 '25 02:10

Prasad


2 Answers

Select * from Students where roll_no like '__2011%' and (subject1 ='maths' or subject2='maths' or subject3='maths' or subject4='maths' or subject5='maths' or subject6='maths');
like image 116
Teja Avatar answered Oct 21 '25 15:10

Teja


When you have multiple or conditions, in is a cleaner way to handle this:

Select * 
from Students 
where 
    roll_no like '__2011%' and 
    'maths' in (subject1, subject2, subject3, subject4, subject5, subject6);
like image 21
Michael Fredrickson Avatar answered Oct 21 '25 17:10

Michael Fredrickson