1

The code below works like it should, but now I want to add multiple dates like this:

reservationStartDate = 2018-07-16, 2018-07-17

SELECT 
    *,
    SUM(IF(reservationId IS NULL,
        0,
        reservationStartDate = '2018-07-17')) AS ConflictingReservations
FROM
    units
        LEFT JOIN
    reservations ON (unitsId = reservationSpace)
WHERE
    unitsType = 'room1'
GROUP BY unitsId
HAVING ConflictingReservations = 0;
2
  • 1
    Use IN clause. Commented Jul 2, 2018 at 15:18
  • @PM77-1 In an IF statement? Commented Jul 2, 2018 at 15:19

2 Answers 2

2

I would just do:

SELECT u.unit_id,
       SUM(r.reservationStartDate IN ('2018-07-17')) AS ConflictingReservations
FROM units u LEFT JOIN
     reservations r
     ON u.unitsId = r.reservationSpace
WHERE u.unitsType = 'room1'
GROUP BY u.unitsId
HAVING ConflictingReservations = 0;

Or, even more simply:

SELECT u.*
FROM units u LEFT JOIN
     reservations r
     ON u.unitsId = r.reservationSpace AND
        r.reservationStartDate in ( . . . )
WHERE u.unitsType = 'room1' AND r.reservationSpace IS NULL;

No GROUP BY is needed at all, because you are not using the count.

Sign up to request clarification or add additional context in comments.

Comments

1

Use OR

(reservationStartDate = '2018-07-16' OR reservationStartDate = '2018-07-17')

The complete query would be

SELECT 
    *,
    SUM(IF(reservationId IS NULL,
        0,
        (reservationStartDate = '2018-07-17'
            OR reservationStartDate = '2018-07-17'))) AS ConflictingReservations
FROM
    units
        LEFT JOIN
    reservations ON (unitsId = reservationSpace)
WHERE
    unitsType = 'room1'
GROUP BY unitsId
HAVING ConflictingReservations = 0;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.