简体   繁体   English

如何在MySQL查询中尽可能覆盖值

[英]How to override values if possible in mysql query

I try to store the working hours of employees in a mysql table. 我尝试将员工的工作时间存储在mysql表中。 In the table working_hour i store the normal working hours: 在表working_hour我存储正常工作时间:

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: working_hour_specia l表如下所示:

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. 与1月1日第1周的周日相比,7月26日这一周没有区别。

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. 其次,当您有一个左联接,然后将该表放入WHERE子句(不考虑对NULL进行测试)时,它基本上会创建一个普通的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. 因此,您可能正在寻找的是将与SPECIAL相关联的WHERE组件转换为条件的JOIN部分……类似。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM