简体   繁体   中英

How to store working days and check if a date matches that day

I'm using postgres and trying to understand how to store and also query against working days.

I have an attribute on my users table called working_days which is an int array.

If a person only works on Monday and Wednesday, then I will store [0, 2]

If I want to know which users are available to work "today" which happens to be a Tuesday, I want to find users who have working_hours of [1] .

How can I get the day from the date, and is there some better way to do this?

SELECT *
FROM users
WHERE working_days &&
      ARRAY[
         CAST((extract(dow FROM current_timestamp) + 1) % 7
               AS integer
         )
      ];

This uses the "array overlaps" operator && with a one-element array constructed from the current week day.

A GIN index on working_days can speed up the query.

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