2017-02-14 73 views
0

我有一張可以在多個部分工作的員工表。但是,一旦一個部分是徒勞的,日期/秒,他們是不可用於在其他部分預訂該日期MySQL查詢員工的可用性

Employee表是員工

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.)顯示當選擇日期範圍且該範圍內沒有預訂時員工可用。

我可以得到一部分一個,而不是部分

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

再次感謝您的幫助!

- 李

+0

我可以問你爲什麼使用id_resources而不是id_sections? – FreedomPride

回答

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) 

然後你做相反的。