MySQL实战基础知识入门(10):今天、昨天、近7天、近30天在一个筛选语句内实现的解决方案

完整代码:

        $sql = "select SUM(a.should_paid) AS totalPays,a.id,a.leader_id,b.userid,b.name,c.order_id,c.status from " . $db->table('orders');
        switch ($CR_days) {
            case -1;
                $sql .= "  AND TO_DAYS(curdate()) - TO_DAYS(date_format(a.paid_at,'%Y-%m-%d')) = 1";
                break;
            case 0;
                $sql .= "  AND date_format(a.paid_at,'%Y-%m-%d') = curdate()";
                break;
            case 7;
                $sql .= "  AND DATE_SUB(curdate(), INTERVAL 6 DAY) <= date(a.paid_at)";
                break;
            case 30;
                $sql .= "  AND DATE_SUB(curdate(), INTERVAL 29 DAY) <= date(a.paid_at)";
                break;
            case "100";//全部信息;
                break;
            default:
                $sql .= "  AND date_format(a.paid_at,'%Y-%m-%d') = curdate()";
        }
        $sql .= " GROUP BY a.leader_id ORDER BY totalPays DESC";
        $row = $db->queryall($sql);

代码分解:

  1. PHP代码连接的小技巧,对$sql进行分解,视图整洁,也便于查看:
 $sql .= 
  1. switch条件语句的使用,实现一条语句实现多个条件查询
 switch ($CR_days) 
            case 0;
             break;
     default:
  1. 昨天
 $sql .= "  AND TO_DAYS(curdate()) - TO_DAYS(date_format(a.paid_at,'%Y-%m-%d')) = 1";
  1. 今天
$sql .= "  AND date_format(a.paid_at,'%Y-%m-%d') = curdate()";
  1. 近7天
  $sql .= "  AND DATE_SUB(curdate(), INTERVAL 6 DAY) <= date(a.paid_at)";
  1. 近30天
$sql .= "  AND DATE_SUB(curdate(), INTERVAL 29 DAY) <= date(a.paid_at)";

Done!

你可能感兴趣的:(mysql)