MySQL有时会搜索null

时间:2019-01-30 10:31:29

标签: php mysql null

我的mySQL有一个小问题:

   if ($rooflightReportSalesReleaseFromDate !== "" ) {
       $sql .= "AND (date(orderRelease.Sales_Release_Date)) >= '" . $rooflightReportSalesReleaseFromDate
             . "' OR orderRelease.Sales_Release_Date IS NULL" ;
   }
   if ($rooflightReportSalesReleaseToDate !== "") {
       $sql .= " AND (date(orderRelease.Sales_Release_Date)) <= '" . $rooflightReportSalesReleaseToDate
       . "' OR orderRelease.Sales_Release_Date IS NULL";
   }

$ rooflightReportSalesReleaseToDate和$ rooflightReportSalesReleaseFromDate有时为空,但是我想知道两个日期是否都具有值,但它仍返回null(可能是因为OR语句)。有没有一种方法可以处理空/空记录,因为如果我没有or语句(或者空检查是独立的),我会报错

谢谢。

1 个答案:

答案 0 :(得分:1)

您正在混合AND和OR,因此很可能是运算符优先级问题。只需在OR运算符周围加上括号即可:

if ($rooflightReportSalesReleaseFromDate !== "" ) {
    $sql .= "AND (
        date(orderRelease.Sales_Release_Date) >= '" . $rooflightReportSalesReleaseFromDate . "'
        OR orderRelease.Sales_Release_Date IS NULL
    )" ;
}
if ($rooflightReportSalesReleaseToDate !== "") {
    $sql .= " AND (
        date(orderRelease.Sales_Release_Date) <= '" . $rooflightReportSalesReleaseToDate . "'
        OR orderRelease.Sales_Release_Date IS NULL
    )";
}

话虽如此,假设Sales_Release_Date包含日期和时间,而变量仅包含日期,则可以像这样消除date()强制转换:

if ($rooflightReportSalesReleaseFromDate !== "" ) {
    $sql .= " AND (orderRelease.Sales_Release_Date >= '" . $rooflightReportSalesReleaseFromDate . "' OR orderRelease.Sales_Release_Date IS NULL)" ;
}
if ($rooflightReportSalesReleaseToDate !== "") {
    $sql .= " AND (orderRelease.Sales_Release_Date < '" . $rooflightReportSalesReleaseToDate . "' + INTERVAL 1 DAY OR orderRelease.Sales_Release_Date IS NULL)";
    // check for less than only -------------------^                                              ^
    // add one day to end date --------------------------------------------------------------------
}