无法在mysql中获取一个月的所有日期

时间:2014-06-04 10:04:12

标签: mysql sql database stored-procedures

我想制作一个能在一个月内显示员工出勤率的计划。如果只显示员工在场的那天,我可以这样做,但我想显示员工不在场的日期(缺席)。 我有像这样的MySQL查询

SELECT x.Tanggal
        , TIME(a.EventTime) AS TimeIn
FROM
(SELECT  Tanggal FROM (
SELECT DATE_ADD('2014-05-01', INTERVAL n5.num*10000+n4.num*1000+n3.num*100+n2.num*10+n1.num DAY ) AS Tanggal FROM
(SELECT 0 AS num
   UNION ALL SELECT 1
   UNION ALL SELECT 2
   UNION ALL SELECT 3
   UNION ALL SELECT 4
   UNION ALL SELECT 5
   UNION ALL SELECT 6
   UNION ALL SELECT 7
   UNION ALL SELECT 8
   UNION ALL SELECT 9) n1,
(SELECT 0 AS num
   UNION ALL SELECT 1
   UNION ALL SELECT 2
   UNION ALL SELECT 3
   UNION ALL SELECT 4
   UNION ALL SELECT 5
   UNION ALL SELECT 6
   UNION ALL SELECT 7
   UNION ALL SELECT 8
   UNION ALL SELECT 9) n2,
(SELECT 0 AS num
   UNION ALL SELECT 1
   UNION ALL SELECT 2
   UNION ALL SELECT 3
   UNION ALL SELECT 4
   UNION ALL SELECT 5
   UNION ALL SELECT 6
   UNION ALL SELECT 7
   UNION ALL SELECT 8
   UNION ALL SELECT 9) n3,
(SELECT 0 AS num
   UNION ALL SELECT 1
   UNION ALL SELECT 2
   UNION ALL SELECT 3
   UNION ALL SELECT 4
   UNION ALL SELECT 5
   UNION ALL SELECT 6
   UNION ALL SELECT 7
   UNION ALL SELECT 8
   UNION ALL SELECT 9) n4,
(SELECT 0 AS num
   UNION ALL SELECT 1
   UNION ALL SELECT 2
   UNION ALL SELECT 3
   UNION ALL SELECT 4
   UNION ALL SELECT 5
   UNION ALL SELECT 6
   UNION ALL SELECT 7
   UNION ALL SELECT 8
   UNION ALL SELECT 9) n5
) a
WHERE (Tanggal BETWEEN '2014-05-01' AND '2014-05-31')) x
LEFT JOIN VW_AttendanceIN a ON DATE(a.EventTime)=x.Tanggal
WHERE a.EmployeeID='90443'
AND (DATE(a.EventTime) BETWEEN '2014-05-01' AND '2014-05-31')
GROUP BY x.Tanggal

但是,结果只是给出了这样的当前日期

结果:

|   Tanggal  |  TimeIn  |
| 2014-05-01 | 08:00:00 |
| 2014-05-02 | 08:00:00 |
| 2014-05-05 | 08:00:00 |
| 2014-05-06 | 08:00:00 |
| 2014-05-07 | 08:00:00 |

第3和第4名未列出 我想要这样的结果

|   Tanggal  |  TimeIn  |
| 2014-05-01 | 08:00:00 |
| 2014-05-02 | 08:00:00 |
| 2014-05-03 |   NULL   |
| 2014-05-04 |   NULL   |
| 2014-05-05 | 08:00:00 |
| 2014-05-06 | 08:00:00 |
| 2014-05-07 | 08:00:00 |

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

解决方案

你需要替换它:

LEFT JOIN VW_AttendanceIN a ON DATE(a.EventTime)=x.Tanggal
WHERE a.EmployeeID='90443'
AND (DATE(a.EventTime) BETWEEN '2014-05-01' AND '2014-05-31')

以下内容:

LEFT JOIN VW_AttendanceIN a ON DATE(a.EventTime)=x.Tanggal AND a.EmployeeID='90443'

原因

WHERE子句中的联接表的引用会筛选出最终结果集行,而不会从已连接表中匹配行,即它不允许a.EmployeeIDa.EventTime为{{ 1}}。如果将这些引用放在NULL的{​​{1}}子句中,则不是这种情况,因为它过滤掉了联接表中的行而不是最终结果集中的行。