具有多个ands和ors的Mysql查询

时间:2013-05-27 04:22:45

标签: php mysql

我正在尝试为我网站上的服务器创建过滤功能。用户可以检查他们想要过滤的类别的不同选项,并且我有一个ajax请求,返回满足其条件的服务器。但是,我的mysql_query无效,我想我的语法可能不正确。

默认情况下,每个类别都将选项设置为1.我当前的查询是:

$order = "SELECT * FROM `servers` 
    WHERE `size` = '$size' or 
      1 = '$size' and 
      `type` = '$type' or 
      1 = '$type' and 
      `mode` = '$gamemode' or 
      1 = '$gamemode' and 
      `main` = '$main' or 
      1 = '$main' 
    ORDER BY $orderby 
    LIMIT 5";

它似乎没有得到正确的服务器,我的查询中是否有错误?

谢谢!

5 个答案:

答案 0 :(得分:5)

在查询中混合andor时,必须使用括号对条件进行分组。另外,我想当你说1 ='$ size'时,我认为你的意思是`size`=1

$order = "SELECT * FROM `servers` 
WHERE 
  (`size` = '$size' or `size` = '1') and 
  (`type` = '$type' or `type` = 1) and 
  (`mode` = '$gamemode' or `mode`= 1 ) and 
  (`main` = '$main' or `main` = 1) 
ORDER BY $orderby 
LIMIT 5";

答案 1 :(得分:2)

"SELECT * FROM `servers` WHERE 
`size` in ('$size', 1) and 
`type` in( '$type' ,1) and 
`mode` in('$gamemode' ,1) and 
`main` in ( '$main' , 1 ) 
ORDER BY $orderby LIMIT 5";

答案 2 :(得分:1)

您需要添加括号,因为orand具有不同的操作顺序,需要使用括号来允许您需要完成的操作

SELECT * FROM `servers` WHERE
(`size` = '$size' or 1 = '$size') and
(`type` = '$type' or 1 = '$type') and
(`mode` = '$gamemode' or 1 = '$gamemode') and
(`main` = '$main' or 1 = '$main')
ORDER BY $orderby LIMIT 5

答案 3 :(得分:0)

试着围绕or条件

$order = "SELECT * FROM `servers` WHERE (`size` = '$size' or 1 = '$size') and (`type` = '$type' or 1 = '$type') and (`mode` = '$gamemode' or 1 = '$gamemode') and (`main` = '$main' or 1 = '$main') ORDER BY '$orderby' LIMIT 5";

答案 4 :(得分:0)

您必须使用括号在查询中使用多个OR条件

mysql_query("SELECT * FROM servers WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo')");

您可以使用列名更改

你也可以像

一样使用IN condtion
mysql_query("SELECT * FROM servers WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo')");

请告诉我,如果我可以帮助你更多

相关问题