3

I have following MySQL queries:

SELECT * 
FROM bookings 
WHERE record_id = 7 AND status = 'available' AND startdate >= '2015-05-02' AND startdate <= '2015-05-09'
UNION ALL
SELECT * 
FROM bookings 
WHERE record_id = 7 AND status = 'available' AND startdate >= '2015-05-11' AND startdate <= '2015-05-12'

Is it possible to combine these two queries, instead of using UNION ALL ?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
djmzfKnm
  • 26,679
  • 70
  • 166
  • 227

4 Answers4

2

You can use OR operator instead as below

SELECT * 
FROM bookings 
WHERE record_id = 7 
AND status = 'available' 
AND ((startdate >= '2015-05-11' AND startdate <= '2015-05-12') or (startdate >= '2015-05-02' AND startdate <= '2015-05-09'))
Robert
  • 25,425
  • 8
  • 67
  • 81
2

This schould work:

SELECT * 
FROM bookings 
WHERE record_id = 7 AND status = 'available' AND 
   ((startdate >= '2015-05-02' AND startdate <= '2015-05-09') or (startdate >= '2015-05-11' AND startdate <= '2015-05-12'))
Jens
  • 67,715
  • 15
  • 98
  • 113
2

You could just use an OR operator to get both date ranges:

SELECT * 
FROM   bookings 
WHERE  record_id = 7 AND
       status = 'available' AND 
       ((startdate >= '2015-05-02' AND startdate <= '2015-05-09') OR
        (startdate >= '2015-05-11' AND startdate <= '2015-05-12'))
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Leave this part:

SELECT * FROM bookings WHERE record_id = 7 AND status = 'available'

Add this:

AND ((startdate >= '2015-05-02' AND startdate <= '2015-05-09') OR (startdate >= '2015-05-11' AND startdate <= '2015-05-12'))

OR condition will return true if you get a true for the first and condition Or the second and condition

Also for those and conditions you are using you might want to take a look at the sql BETWEEN statement : http://www.w3schools.com/sql/sql_between.asp

You could also do this after your first part:

AND startDate >= '2015-05-02' AND startDate <= '2015-05-12' AND NOT startDate = '2015-05-10'

As you are using hard coded dates anyways and the only one in that range you don't need is the 10th of May

Jeremy C.
  • 2,405
  • 1
  • 12
  • 28