1

I'm trying to do something like that

SELECT build.id as build_id, build.name, city.city_name as city, hours.day, hours.start, hours.end FROM Buildings AS build 
LEFT JOIN Cities city ON city.id=build.city_id 
JOIN OperatingHours hours ON hours.build_id=build.id 
WHERE city.id = 3
AND ( hours.day=4 AND ('20:00:00') BETWEEN hours.start AND hours.end)
AND ( hours.day=3 AND ('08:00:00') BETWEEN hours.start AND hours.end)

Is it way to do it?

1
  • 1
    Sample data and desired results would help. Commented Dec 21, 2019 at 17:38

1 Answer 1

1

Assuming that you want buildings that are open at those two times, then use aggregation:

SELECT b.id as build_id, b.name, c.city_name as city
FROM Buildings b LEFT JOIN
     Cities c
     ON c.id = b.city_id JOIN
     OperatingHours h
     ON h.build_id = b.id 
WHERE city.id = 3
GROUP BY b.build_id
HAVING COUNT(*) FILTER (WHERE h.day = 4 AND '20:00:00' BETWEEN h.start AND h.end) > 0 AND
       COUNT(*) FILTER (WHERE h.day = 3 AND '08:00:00' BETWEEN h.start AND h.end) > 0;

If you want to include the hours and days in the results, then you need to aggregate them. I would recommend array_agg().

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

1 Comment

Yes, exactly what i need. Thanks!

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.