选择适合时间表mysql的用户

时间:2013-03-08 10:08:05

标签: mysql select timetable

我需要选择所有“适合”他们工作时间表的用户。

MySQL中的表格 的时间表:

user_id                           PRIMARY
day_number(0-sunday 6-saturday)   PRIMARY (one user - one day)
start                             start worktime 
end                               end worktime

示例用户:

user_id    = 1
day_number = 1
start      = 10:00
end        = 18:00

user_id    = 1
day_number = 2
start      = 12:00
end        = 18:00

user_id    = 1
day_number = 3
start      = 14:00
end        = 16:00

现在我想要选择从1(星期一)到3(星期三)14:00到16:00 工作的每个用户。 应包含示例用户(ID为1)。

任何想法?

3 个答案:

答案 0 :(得分:1)

SELECT user_id
FROM   my_table
  NATURAL JOIN (SELECT 1 day_number UNION ALL SELECT 2 UNION ALL SELECT 3) days
  JOIN (SELECT MAKETIME(14,0,0) start, MAKETIME(16,0,0) end) times
    ON my_table.start <= times.start
   AND my_table.end   >= times.end
GROUP BY user_id
HAVING   COUNT(DISTINCT my_table.day_number) = 3 -- number of days in range

sqlfiddle上查看。

答案 1 :(得分:1)

尝试此查询

SELECT * 
FROM  `Timetable` 
WHERE day_number between 
 1 and 3 
AND TIME_TO_SEC( start ) <= TIME_TO_SEC(  '14:00' ) 
AND TIME_TO_SEC( end ) >= TIME_TO_SEC(  '16:00' ) 

或者

SELECT * 
FROM  `Timetable` 
WHERE day_number in (1,2,3 )
AND TIME_TO_SEC( start ) <= TIME_TO_SEC(  '14:00' ) 
AND TIME_TO_SEC( end ) >= TIME_TO_SEC(  '16:00' ) 

答案 2 :(得分:0)

请尝试以下代码:

Select * from Timetable
Where day_number>=1 and day_number <=3 And
hour(start) >= 12 and hour(end)<= 16