Thavarith
Thavarith

Reputation: 287

MySQL: Finding the missing values from tables

I have two different tables:

  1. checkin_out consists of two fields: emp_code, checked_date
  2. temp_days consists of two fields: id, date_value

Table checkin_out has following data:

emp_code | checked_date
-----------------------
001        2012-11-01
001        2012-11-02
001        2012-11-03
002        2012-11-01
003        2012-11-01
003        2012-11-02

While table temp_days has following data:

id  | date_value
-----------------
1     2012-11-01
2     2012-11-02
3     2012-11-03
4     2012-11-04
5     2012-11-05

From the above tables, I need to show the missing dates in the table temp_days; I need to query to get a result as follow:

emp_code  |  date_value
-----------------------
001          2012-11-04
001          2012-11-05
002          2012-11-02
002          2012-11-03
002          2012-11-04
002          2012-11-05
003          2012-11-03
003          2012-11-04
003          2012-11-05

If anyone could help, please! Thanks!

Upvotes: 0

Views: 172

Answers (2)

Will A
Will A

Reputation: 24988

The below works for a more complex data set with multiple emp_codes.

SELECT  alldays.emp_code, alldays.date_value
FROM    (
          SELECT date_value, emp_code
          FROM temp_days
          CROSS JOIN checkin_out
          GROUP BY date_value, emp_code
        ) alldays
        LEFT JOIN checkin_out C
            ON alldays.date_value = C.checked_date
            AND alldays.emp_code = C.emp_code
WHERE   C.emp_code IS NULL

Upvotes: 1

John Woo
John Woo

Reputation: 263703

SELECT  c.emp_code, a.date_value
FROM    temp_days a
        LEFT JOIN checkin_out b
            ON a.date_value = b.checked_date
        CROSS JOIN 
        (
            SELECT emp_code
            FROM checkin_out
            GROUP BY emp_code
        ) c
WHERE   b.emp_code IS NULL

Upvotes: 0

Related Questions