我设计了一个数据库模式来保存患者约会。每小时被分成相等的15个插槽,最后两个插槽在紧急情况下始终保持未使用状态。打印预约列表时,我需要预约所有约会以及14行的空行。每小时第15个位置,因此接待员可以在打印的纸张上手工填写计划外的预约。
appt_schedules:
id
slot_id
hour
scheduled_on
插槽表 - 始终包含15行。
id
start_time
end_time
以下查询给出了预期的结果,除了14&的空行。第15个插槽。
SELECT `appt_schedules`.* FROM `appt_schedules`
LEFT JOIN `slots` ON `appt_schedules`.`slot_id` = `slots`.`id`
WHERE `scheduled_on`='2015-04-17' LIMIT 10,10
我也对模式更改持开放态度,这可以带来简单有效的查询。
答案 0 :(得分:0)
SELECT `appt_schedules`.*, `slots`.`slot_id` FROM `appt_schedules`
LEFT JOIN `slots` ON `appt_schedules`.`slot_id` = `slots`.`id`
WHERE `scheduled_on`='2015-04-17' and `slots`.`slot_id` between 1 and 15
假设cours slots.slot_id将15个相等的alots保持为int 1到15
另一种更优化的写法是:
SELECT `appt_schedules`.*, `slots`.`slot_id` FROM `appt_schedules`
LEFT JOIN `slots` ON `appt_schedules`.`slot_id` = `slots`.`id`
WHERE `scheduled_on`='2015-04-17' and `slots`.`slot_id` IS NOT NULL
甚至更好:
SELECT `appt_schedules`.*, `slots`.`slot_id` FROM `appt_schedules`
JOIN `slots` ON `appt_schedules`.`slot_id` = `slots`.`id`
WHERE `scheduled_on`='2015-04-17'
**** BEGIN REVISED EDIT ****
如果我理解正确,请尝试:
SELECT s.slot_id, aps.* FROM slots s
LEFT JOIN
(SELECT *, ROW_NUMBER()
over(PARTITION BY aps.slot_id
ORDER BY aps.slot_id
,aps.scheduled_on) AS RowId
FROM appt_schedules aps) aps
ON aps.slot_id = s.id
AND s.slot_id = aps.RowId
WHERE scheduled_on = '2015-04-17'
ORDER BY s.slot_id
再次感谢您删除slos.slot_id ....
select *
from slots s
left join appt_schedules as
on s.id = as.slot_id
where IFNULL(as.scheduled_on, '') in ('', '2015-04-17')