mysql左外连接

时间:2010-06-17 04:19:26

标签: mysql

我有两张桌子:

  1. employee,其字段为employee_id,firstname,middlename,lastname
  2. timecard包含字段employee_id,time-in,time-out,tc_date_transaction
  3. 我想选择具有相同employee_id的所有员工记录,其中timecard和date与当前日期相同。如果没有与当前日期相等的记录,那么即使没有time-in,timeout和tc_date_transaction,也会返回员工的记录。

    我有这样的查询

    SELECT * 
      FROM employee LEFT OUTER JOIN timecard 
           ON employee.employee_id = timecard.employee_id
     WHERE tc_date_transaction = "17/06/2010";
    

    结果应该是这样的:

    employee_id | firstname | middlename | lastname | time-in | time-out | tc_date_transaction
    ------------------------------------------------------------------------------------------
         1      | john      | t          | cruz     | 08:00   | 05:00    | 17/06/2010     
         2      | mary      | j          | von      | null    | null     | null
    

1 个答案:

答案 0 :(得分:20)

您正在过滤tc_date_transaction,它会过滤此字段中的所有空值,即使是由外连接生成的那些值也会因此失败。将过滤器“tc_date_transaction =”17/06/2010“”移动到join子句中,它将起作用。

SELECT * 
  FROM employee LEFT OUTER JOIN timecard 
       ON employee.employee_id = timecard.employee_id and tc_date_transaction = "17/06/2010";

或写

SELECT * 
  FROM employee LEFT OUTER JOIN timecard 
       ON employee.employee_id = timecard.employee_id 
  where (tc_date_transaction = "17/06/2010" or tc_date_transaction is null);