MySQL查询员工的可用性

时间:2017-02-14 06:21:24

标签: mysql sql

我有一张员工表,可以分多个部分工作。但是,一旦某个部分被预订了日期,他们将无法在该日期的其他部分预订

员工表是员工

id_resources    id_sections EmployeeName    Section
28                25          Mark          Section Two
28                26          Mark          Section Three
28                28          Mark          Section Four
28                29          Mark          Section Five
28                53          Mark          Section Six
28                64          Mark          Section Seven
28                74          Mark          Section Eight
28                76          Mark          Section Nine
29                30          Blair         Section One
29                47          Blair         Section Two
29                49          Blair         Section Three
30                82          Sam           Section One
30                25          Sam           Section Two
30                28          Sam           Section Three
30                29          Sam           Section Four
31                18          David         Section Eleven
31                19          David         Section One
31                22          David         Section Two
31                25          David         Section Three

然后我的预订表是预订

id_resources    id_sections startdate   enddate
28                 25      2016-09-09   2016-09-09
28                 26      2016-09-20   2016-09-20
28                 28      2016-10-17   2016-10-17
30                 82      2016-10-18   2016-10-18
30                 25      2016-10-28   2016-10-28
29                 30      2016-11-02   2016-11-02
29                 47      2016-11-07   2016-11-07
29                 49      2016-11-01   2016-11-01
29                 58      2017-01-09   2017-01-09

所以我遇到的问题是让员工成为:

A。)如果每天预订一个部分,则不适用于所有部分  B.)当选择了日期范围并且没有该范围的预订时,将员工显示为可用。

我可以参加 A ,但不能参加 B

Select *
FROM employees
LEFT JOIN bookings on employees.id_resources = bookings.id_resources
WHERE
   (Select..... and i get lost here

再次感谢您的帮助!

-Lee

1 个答案:

答案 0 :(得分:0)

你应该尝试类似的东西:

SELECT employees.*
FROM employees
    LEFT OUTER JOIN bookings 
    ON employees.id_resources = bookings.id_resources 
        AND (
        (startdate BETWEEN $start_range AND $end_range)
        OR 
        (enddate BETWEEN $start_range AND $end_range)
        )
WHERE bookings.id_resources IS NULL

快速解释:我们使用LEFT OUTER JOIN ... WHERE ... IS NULL为排除。 This post可能会帮助您

修改:当您使用LEFT OUTER JOIN作为排除项首先时,您必须考虑与目标相反的情况。在这里,它将找到在两个日期之间预订的用户。为此,您将收到如下查询:

SELECT employees.*
FROM employees
    INNER JOIN bookings 
    ON employees.id_resources = bookings.id_resources 
        AND (startdate BETWEEN $start_range AND $end_range)
        AND (enddate BETWEEN $start_range AND $end_range)

然后你做相反的事。