如何从数据库中获取在特定日期和时间内未分配的用户列表


How to fetch those user list which are not assigned during particular date and time from database

我尝试了很多逻辑,但仍然没有得到准确的结果。我有两个字段shift_from和shift_to与日期时间。相同的字段也存在于数据库中。现在我必须检查哪些用户在特定的时间内没有被分配任何班次。

预期结果:查询应返回在输入的日期和时间内未被占用的用户列表。

使用

表:

  1. users -包含用户日期
  2. role_users -确定用户的角色。
  3. roles -确定角色列表。
  4. shift-确定班次细节,如时间,日期,地点等。
  5. company -仅识别与公司相关的用户。

注意:我得到shift_from datetime从一个表单和shift_to datetime从。

我的努力:我的查询如下:

SELECT u.id,u.name FROM users as u
left join role_user as ru on u.id=ru.user_id 
left join roles as r on ru.role_id=r.id
left join shift_assignment as saa on saa.user_id=u.id
left join shifts as s on s.id=saa.shift_id 
left join companies as c on u.company_id= c.id 
WHERE r.name='security_officer_agents' and 
c.id=$company_id and ((DATE('$shift_from_date') NOT BETWEEN DATE('s.shift_from') and DATE('s.shift_to') and TIME('$shift_from_time') NOT BETWEEN TIME('s.shift_from') and TIME('s.shift_to')) or (DATE('$shift_to_date') NOT BETWEEN DATE('s.shift_from') and DATE('s.shift_to') and TIME('$shift_to_time') NOT BETWEEN TIME('s.shift_from') and TIME('s.shift_to'))

请帮我一下。还有一种方法可以避免not between,因为它不考虑那一天,它只考虑这两个日期之间的时间。

表结构
'id', 
`location_id` ,   
`duty_point_id`,    
`contact`,    
`phone`,   
`shift_from`,    
`shift_to` ,    
`created_by` ,    
`created_at`,     
`updated_at`,   
 PRIMARY KEY (`id`),    
KEY    `shifts_location_id_foreign` (`location_id`)

你可以这样应用条件,

fromtimedbfieldname < '$endtimephpvarible' 
AND 
totimedbfieldname > '$starttimephpvarible'

这个条件解决了你的问题。

s.shift_from < $shift_to_date
AND
s.shift_to > shift_from_date
像上面的

你必须替换。如果user在这些日期之间被分配,它将返回true。

$shift_to_date=date("Y-m-d H:i:s",strtotime($shift_to_date))