I’m working on a project that must store employees’ timetables. For example, one employee works Monday through Thursday from 8am to 2pm and from 4pm to 8pm. Another employee may work Tuesday through Saturday from 6am to 3pm.
I’m looking for an algorithm or a method to store these kind of data in a MySQL database. These data will be rarely accessed so it’s not important performance questions.
I’ve thought to store it as a string but I don’t know any algorithm to “encode” and “decode” this string.
As many of the comments indicate, it’s usually a poor idea to encode all the data into a string that is basically meaningless to the data base. It’s usually better to define the data elements and their relations and represent these structures in the data base. The Wikipedia article on data models is a good overview of what’s involved (although it’s way more general than what you need). The problem you are describing seems simple enough that you could do this with pencil and paper.
One way to start is to write down a lists of logical relationships between concepts in your problem. For instance, the list might look like this (your rules may be different):
From this, you can list the nouns used in the rules. These are candidates for entities (columns) in the data base:
For the rules I listed, schedules seem to exist independently of employees. Since there needs be a way of identifying which schedule an employee follows, it makes sense to add one more entity:
If you then look at the verbs in the rules (“follows”, “has”, etc.), you start to get a handle on the relationships. I would group everything so far into two relationships:
That seems to be all that’s needed by way of data structures. (A reasonable alternative to
start_dayandend_dayfor the Schedules table would be a boolean field for each day of the week.) The next step is to design the indexes. This is driven by the queries you expect to make. You might expect to look up the following:Since employees and schedules are uniquely identified by their respective IDs, these should be the primary fields of their respective tables. You also probably want to have consistency rules for the data. (For instance, you don’t want an employee on a schedule that isn’t defined.) This can be handled by defining a “foreign key” relationship between the
Employees.schedule_IDfield and theSchedules.IDfield, which means thatEmployees.schedule_IDshould be indexed. However, since employees can share the same schedule, it should not be a unique index.If you need to look up schedules by day of week and time of day, those might also be worth indexing. Finally, if you want to look up employees by name, those fields should perhaps be indexed as well.