开发者

using "OR" and "AND" mysql php

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.


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


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


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 


you should use IN Operator

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


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


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 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜