简体   繁体   中英

How to override values if possible in mysql query

I try to store the working hours of employees in a mysql table. In the table working_hour i store the normal working hours:

id employee weekDay    start     end 
1     1       2      10:00:00  18:00:00
2     1       3      10:00:00  18:00:00
3     1       4      10:00:00  14:00:00
4     1       5      10:00:00  12:00:00
5     1       6      10:00:00  18:00:00
6     1       7      00:00:00  00:00:00
7     1       1      00:00:00  00:00:00

In a 2nd table i store "special" working hours. There i store things like illness, holidays or just customized working hours for a specific day. The working_hour_specia l table look like:

id           start                   end            type
2     12013-03-12 00:00:00  2013-03-13 23:59:59      ill

And thats what i have tried:

SELECT 
    IFNULL(working_hour_special.start, working_hour.start) AS startTime,
    IFNULL(working_hour_special.end, working_hour.end) AS endTime,
    type
FROM 
    working_hour_special LEFT JOIN
    working_hour ON working_hour.employee_id = working_hour_special.employee_id
WHERE 
    working_hour_special.start = DATE('2013-03-13') AND 
    employee_id = 1 AND
    working_hour.weekDay = DAYOFWEEK('2013-03-13')

The problem is the WHERE-Clause. I need the start and end time of a specific day for a specific employee. Got somebody an idea how to do that?

First, it appears poor table design. You have just a day of week in one, but a full date/time stamp in the other. Nothing to differentiate betweek day of week 1 for the January 1st week, vs day of week 1 in week of July 26th.

Second, when you have a left-join, and then throw that table into a WHERE clause (without consideration test of a NULL), it basically creates a normal INNER JOIN.

So, what you may be looking for is to shift your WHERE component associated with the SPECIAL to the JOIN part of the condition... something like.

SELECT 
      IFNULL(working_hour_special.start, working_hour.start) AS startTime,
      IFNULL(working_hour_special.end, working_hour.end) AS endTime,
      type
   FROM 
      working_hour_special 
         LEFT JOIN working_hour 
            ON working_hour.employee_id = working_hour_special.employee_id
           AND working_hour_special.start = DATE('2013-03-13')
   WHERE 
          employee_id = 1 
      AND working_hour.weekDay = DAYOFWEEK('2013-03-13')

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