简体   繁体   English

mysql左外连接

[英]mysql left outer join

I have two tables: 我有两张桌子:

  1. employee with fields employee_id, firstname, middlename, lastname employee包含字段employee_id,名字,中间名,姓氏
  2. timecard with fields employee_id,time-in,time-out,tc_date_transaction timecard with fields employee_id,time-in,time-out,tc_date_transaction

I want to select all employee records which have the same employee_id with timecard and date is equal with the current date. 我想选择具有相同employee_id的所有员工记录,其中timecard和date与当前日期相同。 If there are no records equal with the current date then return also the records of employee even without time-in,timeout and tc_date_transaction. 如果没有与当前日期相等的记录,那么即使没有time-in,timeout和tc_date_transaction,也会返回员工的记录。

I have a query like this 我有这样的查询

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

result should like this: 结果应该是这样的:

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

You are filtering tc_date_transaction which filters all null values in this field, even those generated by the outer-join and therefore defeats its purpose. 您正在过滤tc_date_transaction,它会过滤此字段中的所有空值,即使是由外连接生成的那些值,也会因此失败。 Move the filter "tc_date_transaction = "17/06/2010"" into the join clause and it will work. 将过滤器“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";

or write 或写

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

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

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