简体   繁体   English

MySQL在2个日期之间搜索

[英]MySQL search between 2 dates

I am having a wierd issue on a query, I am simply doing a search using 2 dates, I have all the dates in the database formatted in 2012-12-02 00:00:00 mysql format, but it is simply ignoring the AND cslblicstat = '10' AND wcxdate BETWEEN '$date1' AND '$date2' and giving me anything that has the matching class. 我在查询上遇到了一个奇怪的问题,我只是在使用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());

}
}
}

In SQL, AND operator has higher precedence than OR . 在SQL中, AND运算符的优先级高于OR I guess that you just need to put the ORed conditions into parentheses: 我想你只需要将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   

When in doubt about precedence of operators, use parenthesis (or consult the manual). 如果对操作符的优先级有疑问,请使用括号(或参考手册)。

You could also write that condition with IN : 你也可以用IN写这个条件:

WHERE '$key' IN (class1, class2, ... , class12)
  AND user = ''
  ---

In MySQL AND is evaluated before OR. 在MySQL中,在OR之前进行评估。 So your WHERE clause is equivalent to this: 所以你的WHERE子句等价于:

SELECT 1 OR 0 AND 0;

The result is true: 结果是这样的:

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

Also, a syntactically simpler method of expressing your OR conditions would be something like this: 另外,表达OR条件的语法更简单的方法是这样的:

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

But anytime you have columns like that with numbers, what it really means is that your schema can be improved. 但是,只要你有像数字这样的列,它的真正含义是你的架构可以改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM