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