简体   繁体   中英

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. I am having to join 2 tables to do this; hire and 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_items contains the following fields: 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)
$hed is the hire end date (from an input)
$hrd is the hire return date (from an input)

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
  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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