mysql左边连接三个表

时间:2015-06-09 07:17:12

标签: php mysql

假设我有3张桌子:

leave_type:

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

雇员

id       |       name
4        |       Employee 1
7        |       Employee 2

employee_leave_blance

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

此处employee_leave_blance.leave_type_id = leave_type.id

现在我想获得所有员工的所有Leave Type值。

让我举个例子:我想获得employee_id = 4, 7

的输出
employee_id  |    name              |  val
4            |    maternity leave   |  9
4            |    Medical leave     |  5
4            |    Casual Leave      |  4
4            |    Sick Leave        |  0
4            |    honeymoon Leave   |  0
7            |    maternity leave   |  10
7            |    Medical leave     |  0
7            |    Casual Leave      |  0
7            |    Sick Leave        |  0
7            |    honeymoon Leave   |  0

我的查询

SELECT
    lt.name, ifnull(el.val,0) as val , el.employee_id 
FROM leave_type AS lt
    LEFT JOIN employee_leave_balance AS el ON el.leave_type_id = lt.id
AND
    el.year = YEAR(CURDATE()) GROUP BY el.employee_id

3 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT employee_id,leave_name,IFNULL(val,0) as val
FROM

(SELECT e.id as employee_id,l.id as lid,l.name as leave_name
 FROM employee e CROSS JOIN leave_type l) as T1 LEFT JOIN

(SELECT val,employee_id as eid,leave_type_id as lid
 FROM employee_leave_blance elb) as T2 ON T1.employee_id=T2.eid AND T1.lid=T2.lid

ORDER BY employee_id asc,val desc

结果:

employee_id leave_name       val
--------------------------------
4           maternity leave  9
4           Medical leave    5
4           Casual Leave     4
4           Sick Leave       0
4           honeymoon Leave  0
7           maternity leave  10
7           Casual Leave     0
7           honeymoon Leave  0
7           Sick Leave       0
7           Medical leave    0

SQL Fiddle中的示例结果。

答案 1 :(得分:0)

试试此代码

SELECT * FROM leave_type 
INNER JOIN employee_leave_blance on leave_type.id = employee_leave_blance.leave_type_id 
INNER JOIN `employee on employee.id = employee_leave_blance.employee_id

答案 2 :(得分:-1)

我已更新我的回答

更新:

    select lt.name,e.id,elb.val from 
      leave_type as lt, employee as e,employee_leave_blance as elb 
      where e.id = elb.employee_id and lb.leave_type_id = lt.id 
      and elb.year= YEAR(CURDATE()) order by (e.id)

SQL Fiddle

上的示例

运行此查询。我没有试过但我希望它能正常工作

select * from leave_type as lt, employee as e, employee_leave_balance as elb
where e.id = elb.employee_id and elb.leave_type_id = lt.id and e.id = $id