[ACCEPTED]-using "OR" and "AND" mysql php-mysql

Accepted answer
Score: 30

Try this:

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

Or, if you prefer your verbose 5 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 4 integer (which it doesn't seem to be by 3 your query since you've used quotation marks, but 2 here goes anyway), you can even use the 1 BETWEEN keyword to select a range of values:

WHERE
  (id_curso BETWEEN 155 AND 158) AND
  id_pregunta = '1' AND
  respuesta >= 0
Score: 9

You need to group your OR statements so that 1 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
Score: 3

AND has higher priority than OR, you need 1 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 
Score: 2

you should use IN Operator

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

0

Score: 2

Try grouping

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

0

Score: 2

You could try something like this...

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

if you 1 don't want to use IN you can also do this...

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

http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in

More Related questions