[英]count occurences in 2 tables
我有一个名为 tasks (id, date, id_user ) 的表。 我还有一个名为 calendar (id, date ) 的表。 要查找用户在 2 个日期之间出现日期字段的次数,我使用以下查询:
$test1 = date(Y-m-d', strtotime('-7'));
$test2 = date('Y-m-d');
$query= $connect->prepare("SELECT *, COUNT(*) AS counter FROM tasks WHERE matricule ='".$_SESSION['matricule']."' AND date < '".$test2."' AND date >= '".$test1."' GROUP BY date");
此查询有效。 我还想为不在我的表格任务中但在表格日历中的日期显示 0
您想要计算给定用户在某天范围内执行的日常任务,包括没有任务的天数。
如果你有一个日历表——比如calendar(dt)
,其中dt
是一个date
——你可以这样做:
select c.dt, count(t.date) as counter
from calendar c
left join tasks t
on t.matricule = :matricule
and t.date = c.dt
where c.date >= :start_date and c.date < :end_date
group by c.dt
:matricule
, :start_date
和:end_date
是查询的参数; 你真的应该使用准备好的语句而不是连接查询字符串中的 POST 值,这会将你的代码打开到 SQL 注入。
如果时间范围始终是上周:
where c.date >= current_date - interval 7 day and c.date < current_date
请注意聚合与原始代码的不同之处: select
子句中的列在group by
子句中重复(将聚合的列分开)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.