【问题标题】:SQL Query for available appointment slots over a month一个月内可用预约空档的 SQL 查询
【发布时间】:2012-02-14 05:46:06
【问题描述】:

目前我有一个疑问:

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 次查询。

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

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

表结构 - 约会

字段类型允许 Null 默认值 id int(11) 否
customer_id int(11) 否
associate_id int(11) 是 schedule_id int(11) 否
日期日期编号
结果_id int(11) 是 备注文字编号
is_active tinyint(1) 否 1 created_at 时间戳 No 0000-00-00 00:00:00 updated_at 时间戳 No 0000-00-00 00:00:00

时间表

字段类型允许 Null 默认值 id int(11) 否
showroom_id int(11) 否
day_of_week enum('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday') 否
时间 时间 没有
max_customers int(11) 否
is_active tinyint(1) 否 1 created_at 时间戳 No 0000-00-00 00:00:00 updated_at 时间戳 No 0000-00-00 00:00:00

【问题讨论】:

  • 能否提供两个表的表结构?那些会更好理解......

标签: mysql sql database dynamic-sql


【解决方案1】:

关于我使用@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')

【讨论】:

    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 2022-01-13
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多