mysql左连接两个表

时间:2015-06-07 03:43:35

标签: php mysql

假设我有两张桌子:

leave_type

id       name
1        maternity leave
2        Medical leave
3        Casual Leave
4        Sick Leave
5        honeymoon Leave

employee_leave_blance

id      employee_id      year     leave_type_id     val
1       4                2015      1                9
2       4                2015      2                5
3       8                2015      1                10
4       4                2015      3                4

此处employee_leave_blance.leave_type_id = leave_type.id

现在我想获取employee_id=4

的所有“离开类型”值

employee_leave_blance的{​​{1}}表中,只有3个leave_type条目,但在employee_id=4表中有5个。 我想为一名员工获得5个条目。如果leave_type中没有找到任何条目,则应返回0。

让我举个例子:我想获得employee_leave_blance

的输出
employee_id = 4

为此,我尝试了以下查询:

employee_id      name                val
4                maternity leave     9
4                Medical leave       5
4                Casual Leave        4
4                Sick Leave          0
4                honeymoon Leave     0

然而它返回以下结果:

select
    el.employee_id, lt.name, el.val  from leave_type as lt
    left join employee_leave_blance as el on el.leave_type_id = lt.id
where
    el.year = YEAR(CURDATE()) and el.employee_id = 4

现在我如何获得员工的所有leave_type的值?

1 个答案:

答案 0 :(得分:1)

不确定这是否是您所需要的,请尝试:

select ifnull(el.employee_id,4) as employee_id,
lt.name,ifnull(el.val,0) as val
from leave_type as lt
left join (select year,employee_id,val,leave_type_id 
                    from employee_leave_balance) as el 
                    on el.leave_type_id = lt.id 
                    and el.year = year(curdate()) 
                    and el.employee_id = 4

实际上,您的查询可以进行一些修改。只需将where子句删除到and,因为您已经连接了表并使用ifnull函数返回0表示空值。这是您的查询,但有一些改进:

select
    ifnull(el.employee_id,4) as employee_id, lt.name, ifnull(el.val,0) as val  
from leave_type as lt
    left join employee_leave_balance as el on el.leave_type_id = lt.id
and
    el.year = YEAR(CURDATE()) and el.employee_id = 4