Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using "OR" and "AND" mysql php

Tags:

php

mysql

I have a MySQL query, where I want to get a value, lets say m that can be 'x', 'y' or 'z' and two other variables which need to be exact values. I don't know how to write this.

I don't know if you get the idea, but this is what I have:

SELECT * FROM respuestas 
WHERE id_curso = '155' OR id_curso = '156' OR id_curso= '157' OR id_curso= '158' 
AND id_pregunta='1' AND respuesta>=0

So I need id_curso to be 155 or 156 or 157 or 158 and at the same time, id_pregunta = 1 and respuesta > 0.

I know this is not the way to write it, but I don't know the right way.

like image 816
Dan Stern Avatar asked Apr 15 '11 14:04

Dan Stern


4 Answers

Try this:

WHERE
  id_curso IN('155', '156', '157', '158') AND
  id_pregunta = '1' AND
  respuesta >= 0

Or, if you prefer your verbose way, use a parenthesis:

WHERE
  (id_curso = '155' OR
   id_curso = '156' OR
   id_curso = '157' OR
   id_curso = '158') AND
  id_pregunta = '1' AND
  respuesta >= 0

If id_curso is an integer (which it doesn't seem to be by your query since you've used quotation marks, but here goes anyway), you can even use the BETWEEN keyword to select a range of values:

WHERE
  (id_curso BETWEEN 155 AND 158) AND
  id_pregunta = '1' AND
  respuesta >= 0
like image 144
Emil Vikström Avatar answered Nov 09 '22 01:11

Emil Vikström


You need to group your OR statements so that they form one condition:

SELECT * FROM respuestas WHERE (id_curso= '155' OR id_curso= '156' OR id_curso= '157' OR id_curso= '158') AND id_pregunta='1' AND respuesta>=0
like image 27
jeroen Avatar answered Nov 09 '22 02:11

jeroen


AND has higher priority than OR, you need to use brackets:

SELECT * FROM respuestas WHERE (id_curso= '155' OR id_curso= '156' OR id_curso= '157' OR id_curso= '158') AND id_pregunta='1' AND respuesta>=0 
like image 3
Jan Zyka Avatar answered Nov 09 '22 01:11

Jan Zyka


you should use IN Operator

SELECT * FROM respuestas WHERE id_curso IN (155, 156, 157, 158) AND id_pregunta='1' AND respuesta>=0
like image 2
Dongsheng Cai Avatar answered Nov 09 '22 01:11

Dongsheng Cai