我在查询上遇到了一个奇怪的问题,我只是使用2个日期进行搜索,我将数据库中的所有日期格式化为2012-12-02 00:00:00 mysql格式,但它只是简单忽略AND cslblicstat ='10'和wcxdate BETWEEN'$ date1'和'$ 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());
}
}
}
答案 0 :(得分: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 = ''
---
答案 1 :(得分:1)
在MySQL中,在OR之前进行评估。所以你的WHERE子句等同于:
SELECT 1 OR 0 AND 0;
结果是真的:
+--------------+
| 1 OR 0 AND 0 |
+--------------+
| 1 |
+--------------+
另外,表达OR条件的语法更简单的方法是这样的:
WHERE '$key' IN ( class, class2, class3, ... ) AND ... ;
但是,只要你有像数字这样的列,它的真正含义就是你的架构可以改进。