简体   繁体   English

MySQL-查询数据库的日期范围

[英]MySQL - querying a database for date ranges

I have an inventory system for adding items that can be hired out. 我有一个库存系统,用于添加可以租用的物品。 I am trying to run a MySQL query to see if an item is already out for hire, before adding the new hire to the system. 我正在尝试运行一个MySQL查询,以查看是否有新项目可供出租,然后再将新员工添加到系统中。 I am having to join 2 tables to do this; 我必须加入2个表才能做到这一点; hire and hire_items. 雇用和hire_items。

hire contains the following fields: hire_id, account_id, hire_start_date, hire_end_date, hire_return_date, total_hire_cost, notes and booking date . hire包含以下字段: hire_id, account_id, hire_start_date, hire_end_date, hire_return_date, total_hire_cost, notes and booking date

hire_items contains the following fields: hire_item_id, hire_id, item_id and item_hire_cost . hire_items包含以下字段: hire_item_id, hire_id, item_id and item_hire_cost

I have already tried the following query, which doesn't error, but does allow me to add a hire where items are already hired out: 我已经尝试了以下查询,该查询没有错误,但确实允许我添加一个已经雇用了人员的雇用人员:

SELECT i.item_id
FROM hire_items AS i
INNER JOIN hire AS h ON i.hire_id = h.hire_id
WHERE ((item_id = $selected_item_id) AND ($hsd >= h.hire_start_date AND $hsd <= h.hire_return_date)) OR ((item_id = $selected_item_id) AND ($hed >= h.hire_start_date AND $hed <= h.hire_return_date)) OR ((item_id = $selected_item_id) AND ($hrd >= h.hire_start_date AND $hrd <= h.hire_return_date))

$hsd is the hire start date (from an input) $hsd是雇用开始日期(来自输入)
$hed is the hire end date (from an input) $hed是雇用结束日期(来自输入)
$hrd is the hire return date (from an input) $hrd是录用返回日期(来自输入)

SELECT i.item_id
FROM hire_items AS i
INNER JOIN hire AS h ON i.hire_id = h.hire_id
WHERE (item_id = $selected_item_id)
AND ($hsd NOT BETWEEN h.hire_start_date AND h.hire_return_date) 
AND ($hrd NOT BETWEEN h.hire_start_date AND h.hire_return_date) 
AND (h.hire_start_date NOT BETWEEN CAST($hsd AS DATE) AND CAST($hrd AS DATE))

This queries for 这查询

  1. The correct item by ID, but only once 按ID正确的商品,但只有一次
  2. That the inputted start date is not during a time of hire 输入的开始日期不在租用时间内
  3. That the inputted return date is not during a time of hire 输入的返回日期不在租用时间内
  4. That the inputted start/return time does not enclose a time of hire 输入的开始/返回时间未包含租用时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM