SQL查询中的条件

时间:2018-11-10 06:56:55

标签: php mysql sql

我想创建一个查询,如果DATEDIFF(so_date,actual_delivery)= 3,它将显示单词“ Passed”,否则显示“ Failed”。有人可以帮我吗?

<?php
$hostname="localhost"; 
$username="root";
$password="";
$db = "csl_otd"; 
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query('SELECT so_date,
       actual_delivery,
       case when DATEDIFF(so_date, actual_delivery) = 3 
            then "Passed"
            else "Failed"
       end as status
FROM sales_order
LEFT JOIN dar ON sales_order.dar_numberr = dar.dar_number
WHERE DATEDIFF(so_date, actual_delivery) < 10') as $row) {
echo "<tr>";
echo "<td>" . $row['so_date'] . "</td>";
echo "<td>" . $row['actual_delivery'] . "</td>"; 
echo "<td>" . $row['DATEDIFF(so_date,actual_delivery)'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "</tr>";  
}
?>
</tbody></table>

输出

Date Difference  | Status
2                | Passed
4                | Failed    

1 个答案:

答案 0 :(得分:0)

用例何时

SELECT so_date,actual_delivery,
     DATEDIFF(so_date,actual_delivery) Date_Difference,
    case when  DATEDIFF(so_date,actual_delivery) = 3 
    then "Passed"
    else "Failed" end Status
    FROM sales_order
    LEFT JOIN dar
    ON sales_order.dar_numberr=dar.dar_number
    WHERE DATEDIFF(so_date,actual_delivery)<10

或者如果您使用过,也可以使用(但是校正很少)

SELECT so_date,actual_delivery,DATEDIFF(so_date,actual_delivery),
if ( DATEDIFF(so_date,actual_delivery) = 3 
,'Passed','Failed') status
FROM sales_order
LEFT JOIN dar
ON sales_order.dar_numberr=dar.dar_number
WHERE DATEDIFF(so_date,actual_delivery)<10