计算 2 个表中的出现次数
count occurences in 2 tables
我有一个 table 叫做 tasks (id, date, id_user )。
我还有一个名为 calendar (id, date) 的 table。
要查找用户在 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");
这个查询有效。
我还想为不在我的 table 任务中但在 table 日历
中的日期显示 0
您想计算给定用户在一定天数内执行的日常任务,包括没有任务的天数。
如果您有日历 table - 例如 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
是查询的 参数 ;你真的应该使用准备好的语句而不是在查询字符串中连接 POSTed 值,这会打开你的代码 SQL 注入。
如果时间范围始终是上周:
where c.date >= current_date - interval 7 day and c.date < current_date
请注意聚合与原始代码的不同之处:select
子句中的列在 group by
子句中重复(将聚合的列分开)。
我有一个 table 叫做 tasks (id, date, id_user )。 我还有一个名为 calendar (id, date) 的 table。 要查找用户在 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");
这个查询有效。 我还想为不在我的 table 任务中但在 table 日历
中的日期显示 0您想计算给定用户在一定天数内执行的日常任务,包括没有任务的天数。
如果您有日历 table - 例如 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
是查询的 参数 ;你真的应该使用准备好的语句而不是在查询字符串中连接 POSTed 值,这会打开你的代码 SQL 注入。
如果时间范围始终是上周:
where c.date >= current_date - interval 7 day and c.date < current_date
请注意聚合与原始代码的不同之处:select
子句中的列在 group by
子句中重复(将聚合的列分开)。