Combining all by combining query results

I have the 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'

      

Can these two queries be combined instead of using UNION ALL

?

+3


source to share


4 answers


Instead, you can use the operator OR

as shown 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'))

      

+2


source


This should 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'))

      

+2


source


You can simply use an operator OR

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

      

+2


source


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 the condition will return true if you get a true value for the first and the condition OR the second and the condition

Also for whichever conditions you are using you can take a look at the sql BETWEEN statement: http://www.w3schools.com/sql/sql_between.asp

You can also do this after the first part:

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

      

Since you are using hardcoded dates anyway and the only thing you don't need is May 10th.

+1


source







All Articles