目前我有一个问题:
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 时间戳 否 0000-00-00 00:00:00
updated_at 时间戳 否 0000-00-00 00:00:00
时间表
字段类型允许空默认值
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 时间戳 否 0000-00-00 00:00:00
updated_at 时间戳 否 0000-00-00 00:00:00
最佳答案
为了澄清我的子查询与@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')
关于mysql - 一个月内可用预约空档的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8928227/