一个月内可用预约空档的SQL查询

时间:2012-01-19 15:00:42

标签: mysql sql database dynamic-sql

目前我有一个查询:

select a.day_of_week,
       a.time,
       a.id,
       '2012-01-10' as scheduleDate,
       a.max_customers,
       (SELECT count(b.id) 
        from appointments b 
        where b.date = '2012-01-10' AND 
              b.schedule_id = a.id) as current_customers 
from schedules a 
where a.showroom_id = 1 and
      a.day_of_week = DATE_FORMAT('2012-01-10','%W')

假设'2012-01-10'是可变的。

我们有一个日历应用程序。当用户点击一天时,运行此查询以返回广告位列表和当前预订的人数(current_customers)。

这是怪癖 - 现在他们希望能够一次检索整个月。目前,我们的开发人员基本上通过PHP中的FOR循环执行30次查询。

我正在考虑创建一个存储过程来执行此操作,但您仍在使用循环。联合是另一种选择,但那是我认为的大型查询。

有没有人知道如何创建一个可以运行上述但一个月或可变天数的所有日子的查询?

表格结构 - 约会

字段类型允许空值默认值 id int(11)否
customer_id int(11)否
associate_id int(11)是的 schedule_id int(11)没有
日期日期否
outcome_id int(11)是的 备注文字否
is_active tinyint(1)否1 created_at timestamp No 0000-00-00 00:00:00 updated_at timestamp No 0000-00-00 00:00:00

调度

字段类型允许空值默认值 id int(11)否
showroom_id int(11)没有
day_of_week枚举('星期一','星期二','星期三','星期四','星期五','星期六','星期天')否

时间没有 max_customers int(11)否
is_active tinyint(1)否1 created_at timestamp No 0000-00-00 00:00:00 updated_at timestamp No 0000-00-00 00:00:00

1 个答案:

答案 0 :(得分:0)

有关我的@sqlvars子查询如何工作的说明,请查看类似的预留查找I offered here。子查询只是查看系统中的任何表,以获取与您想要出去的天数一样多的记录...在此示例中,30天。您所要做的就是更改'2012-01-10'的开始日期,或使用“current_date()”,因此它始终从当前日期+30开始,否则不需要参数。

select
      a.day_of_week, 
      a.time, 
      a.id, 
      @r as scheduleDate, 
      a.max_customers, 
      (SELECT count(b.id) 
          from appointments b 
          where b.date = @r 
          AND b.schedule_id = a.id) as current_customers 
   from
      ( SELECT 
                 @r:= date_add(@r, interval 1 day ) OpenDate
            FROM 
                 (select @r := '2012-01-10') vars,
                schedules limit 30 ) JustDates,
      schedules a 
   where 
          a.showroom_id = 1 
      and a.day_of_week = DATE_FORMAT( @r,'%W')
相关问题