1

我在查询中有一个奇怪的问题,我只是使用 2 个日期进行搜索,我将数据库中的所有日期格式化为 2012-12-02 00:00:00 mysql 格式,但它只是忽略了 AND cslblicstat = '10' AND wcxdate BETWEEN '$date1' AND '$date2' 并给我任何具有匹配类的东西。

$user = $session->username;
if(isset($_POST['carrier'])){
$carrier = $_POST['carrier'];
$class[] = $_POST['class'][0];
$date1 = $_POST['date1'];
$date1 = date("Y-m-d 00:01", strtotime($date1));
$date2 = $_POST['date2'];
$date2 = date("Y-m-d 59:59", strtotime($date2));

 foreach( $class as $key){
 $query =   "SELECT * FROM leads WHERE class1 = '$key' OR class2 = '$key' OR class3 = '$key' OR class4 = '$key' OR class5 = '$key' OR class6 = '$key' OR class7 = '$key' OR class8 = '$key' OR class9 = '$key' OR class10 = '$key' OR class11 = '$key' OR class12 = '$key' AND user = '' AND wccompcode = '$carrier' AND cslblicstat = '10' AND wcxdate BETWEEN '$date1' AND '$date2' LIMIT 100";
$sellead = mysql_query($query)or die(mysql_error());
while($leads = mysql_fetch_array($sellead)){

    $arrayl[] = $leads;
    $rowid = $leads['ID'];
    $update = mysql_query("UPDATE leads SET user = '$user' WHERE ID = '$rowid'")or die(mysql_error());

}
}
}
4

2 回答 2

3

在 SQL 中,AND运算符的优先级高于OR. 我想您只需要将 ORed 条件放入括号中:

SELECT * 
FROM leads
WHERE (class1 = '$key' OR class2 = '$key' OR ... OR class12 = '$key')
  AND user = '' 
  AND wccompcode = '$carrier' 
  AND cslblicstat = '10' 
  AND wcxdate BETWEEN '$date1' 
                  AND '$date2' 
LIMIT 100   

如果对运算符的优先级有疑问,请使用括号(或查阅手册)。

您还可以使用以下方式编写该条件IN

WHERE '$key' IN (class1, class2, ... , class12)
  AND user = ''
  ---
于 2012-12-03T01:13:36.787 回答
1

在 MySQL 中,AND 在 OR 之前进行评估。所以你的 WHERE 子句相当于这个:

SELECT 1 OR 0 AND 0;

结果是真的:

+--------------+
| 1 OR 0 AND 0 |
+--------------+
|            1 |
+--------------+

此外,表达 OR 条件的语法更简单的方法是这样的:

WHERE '$key' IN ( class, class2, class3, ... ) AND ... ;

但是,只要您有带有数字的列,它的真正含义是您的架构可以得到改进。

于 2012-12-03T01:14:36.520 回答