使用mysql在一个查询中存在和不存在

时间:2018-09-05 11:38:47

标签: mysql

我有以下mysql查询:

SELECT m.emp_id     AS `Empid` 
     , d.dt        AS `AbsentDate`,
(CASE WHEN p.punch_status IS NULL
                           THEN 'A'
                           ELSE p.punch_status
                  END 

                  )  s
  FROM ( SELECT DATE(t.added_date) AS dt
           FROM pmc_attendance t
        WHERE date(t.added_date) >= '2018-08-01' 
            AND date(t.added_date) < DATE_ADD( '2018-08-31' ,INTERVAL 1 DAY)
          GROUP BY DATE(t.added_date)
          ORDER BY DATE(t.added_date)
       ) d
 CROSS
  JOIN tbl_admin_users m
  LEFT
  JOIN  pmc_attendance p
    ON date(p.added_date) >= d.dt
   AND date(p.added_date) <  d.dt + INTERVAL 1 DAY
   AND p.emp_id = m.emp_id
 WHERE p.emp_id IS NULL  and m.emp_id='000838' group by d.dt
 ORDER
    BY m.emp_id
     , d.dt

这将获取该雇员的所有缺席记录,但我也想显示该雇员的当前日期。 enter image description here

我的SQL记录显示:

Empid     AbsentDate   
000838    2018-08-05
000838    2018-08-05
000838    2018-08-11
000838    2018-08-12
000838    2018-08-15
000838    2018-08-19

我有两个表 1. tbl_admin_users-员工数据存储 2. pmc_attendance-员工的当前记录

1 个答案:

答案 0 :(得分:-1)

正如我在查询中提到的,我已经删除了p.emp_id IS NULL条件。 由于这种情况,您所有具有p.punch_status is not null的记录都会被过滤掉。

因此您可以在下面的查询中尝试

SELECT m.emp_id     AS `Empid` 
     , d.dt        AS `AbsentDate`,
(CASE WHEN p.punch_status IS NULL
                           THEN 'A'
                           ELSE p.punch_status
                  END 

                  )  s
  FROM ( SELECT DATE(t.added_date) AS dt
           FROM pmc_attendance t
        WHERE date(t.added_date) >= '2018-08-01' 
            AND date(t.added_date) < DATE_ADD( '2018-08-31' ,INTERVAL 1 DAY)
          GROUP BY DATE(t.added_date)
          ORDER BY DATE(t.added_date)
       ) d
 CROSS
  JOIN tbl_admin_users m
  LEFT
  JOIN  pmc_attendance p
    ON date(p.added_date) >= d.dt
   AND date(p.added_date) <  d.dt + INTERVAL 1 DAY
   AND p.emp_id = m.emp_id
 WHERE m.emp_id='000838' group by d.dt
 ORDER
    BY m.emp_id
     , d.dt