Search code examples
mysqltimecell

Mysql Function multiple entries in one cell


So I'm working on a schedule system for my job a basically i wanted to know if there is a way where mysql can do something like:

       |Monday  |tuesday|wendsday|total
|Dan   |5am-7am |7am-6pm|6am-11am|
        11am-2pm|       |2pm-7pm |
        5pm-12am|

where i can enter multiple shifts on 1 day for each person in the same cell if needed instead of the name repeating several times like:

    Dan|5-4|
    Dan|6-8|

and if there is a function to calculate total time in one cell with multiple shifts


Solution

  • There is a way (representing the data as string), but you wouldn't want to do this - you will loose all calculations, searches etc. You should not try to represent the data in the database exactly as how it looks on paper. I would make a table like this:

    ShiftID|Person|StartTime|EndTime
    

    Making StartTime & EndTime columns of type DATETIME, you will store not only the HH:mm of a shift's start, but also the day. This is helpful when you have a shift which starts on one day and ends in the next, like starting on Monday 2017-05-15 23:00 and ending on Tuesday 2017-05-16 02:00.

    You can extract the date only from this filed using MySQL DATE() function and select only those entires which start OR end on this day. To calculate the shift's duration you can use MySQL function TIMESTAMPDIFF() You can even use DAYOFWEEK() to get if it is Monday, Tuesday, etc.

    About duplicating the person's name - I would make another table, which will match users with their data to IDs an use ID in the column Person, but for a starter and if your data is not big and if speed is not an issue and if typo errors (like Den instead of Dan) are not a problem ... you could use the name directly in this table.

    After storing the data in a table like this you could represent it as you wish in HTML (or print).