如何从表A中选择与表B不匹配的行(使用时间范围,基于表B)

时间:2016-08-04 16:00:09

标签: mysql phpmyadmin

我是一名学生,试图设计一个能够在某个时间和某天找到所有空房的系统,根据他们学校现有数据库的教授时间表。 对于每个房间,计划从7:30:00 - 19:30:00(00:30:00增量)生成到名为' room_schedule' 的表格。房间的每个时间表都由另一个名为 ' room_details&#39> 的表格中的room_id引用。另一方面, 桌子' room_details'与会议室' prof_schedule' 相关联。教授的时间表记录在现有的表格' prof_schedule'。

这里是表格的样子

    TABLE 'room_schedule'

    day    time_start  time_end    room_id
    MWF    07:00:00    07:30:00    36
    MWF    07:30:00    08:00:00    36
    MWF    08:00:00    08:30:00    36
    MWF    08:30:00    09:00:00    36
    MWF    09:00:00    09:30:00    36
    MWF    09:30:00    10:00:00    36
    MWF    07:00:00    07:30:00    37
    MWF    07:30:00    08:00:00    37
    MWF    08:00:00    08:30:00    37
    MWF    08:30:00    09:00:00    37
    MWF    09:00:00    09:30:00    37
    MWF    09:30:00    10:00:00    37

    TABLE 'room_details'
    room_id     room_name      room       
    36          Biology Room   309   
    37          Physics Room   307


    TABLE 'prof_schedule'
    sched_id   professor       Day  room    time_start  time_end   subj
    1          Jeffrey Smith   MWF  309     8:00:00     9:30:00     Biology
    2          Ben Williams    MWF  307     8:30:00     10:00:00    Physics
    

根据教授的时间表,我希望空置房间的结果是这样的

RESULT vacant rooms
        day    time_start  time_end    room_name
        MWF    07:00:00    07:30:00    Biology Room
        MWF    07:30:00    08:00:00    Biology Room
        MWF    09:30:00    10:00:00    Biology Room
        MWF    07:00:00    07:30:00    Physics Room
        MWF    07:30:00    08:00:00    Physics Room
        MWF    08:00:00    08:30:00    Physics Room
    

我已尝试过以下查询,但它似乎删除了' room_schedule'中的所有记录。来自' prof_schedule'

的time_start和time_end
SELECT day, time_start, time_end,  room_name 
FROM room_details AS rd 
INNER JOIN room_schedule AS rs 
ON rd.room_ID=rs.room_ID 
WHERE (
   (time_start NOT IN(SELECT time_start FROM prof_schedule)) AND 
   (time_end NOT IN (SELECT time_end FROM prof_schedule)) AND 
   (rs.day NOT IN (select day from prof_schedule)) AND 
   (rs.room_id NOT IN (SELECT DISTINCT rd.room_ID from room_details AS rd 
    INNER JOIN prof_schedule AS ps on rd.room=ps.room))
  )

有人可以建议一个显示我提到的结果的查询吗?

P.S。 需要保留第3个表(prof_schedule)的设计,因为他们要将这些从现有系统导入到我正在设计的系统中。

1 个答案:

答案 0 :(得分:-1)

尝试这样的事情让我知道。

SELECT a.day, a.time_start, a.time_end, b.room_name 
FROM `room_schedule` a 
INNER JOIN `room_details` b ON a.room_id = b.room_id
INNER JOIN `prof_schedule` c ON b.room = c.room AND 
IF(a.time_end > c.time_start, a.time_start >= c.time_end, a.time_start < c.time_start)

尝试使用像这样的GROUP BY子句

SELECT a.*, b.room_name 
FROM `room_schedule` a 
INNER JOIN `room_details` b ON a.room_id = b.room_id
INNER JOIN `prof_schedule` c ON b.room = c.room AND 
IF(a.time_end > c.time_start, a.time_start >= c.time_end, a.time_start < c.time_start)
GROUP BY a.room_id, a.time_start, a.time_end
相关问题