2017-08-07 23 views
-1

我有這個表如何加入得到2個表和左數據加入到1個表中的MySQL

tbl_emp 

    ID| name | 
    1 | a | 
    2 | b | 
    3 | c | 
    4 | d | 

tbl_remit 

    ID| remit | 
    1 | 2012-01-01| 
    2 | 2013-01-01| 
    3 | 2012-05-01| 


tbl_report 

    ID| report | 
    1 | 2012-01-01| 
    2 | 2013-01-01| 
    3 | 2012-05-01| 

我要加入他們的所有3 tbl_emp無論是否存在tbl_remit或tbl_report數據。

這裏是我使用,但失敗的碼。

SELECT tbl_emp*, tbl_remit.remit, tbl_report.report from tbl_emp 
left join tbl_emp.ID = tbl_remit.ID LEFT JOIN tbl_emp.ID = tbl_report.ID 

我得到了桌子

ID | remit | report | 
1 | NULL | NULL | 
2 | NULL | NULL | 
3 | NULL | NULL | 
4 | NULL | NULL | 

我需要的表是

ID | remit | report | 
1 |2012-01-01|2012-01-01| 
2 |2013-01-01|2013-01-01| 
3 |2012-05-01|2012-05-01| 
4 | NULL | NULL | 
+0

您加入語法是假的。該查詢真的有用嗎?語法必須是'from

加入在加入' – Jens

+0

'對不起,我忘記輸入ON條件,我無法正確地複製或記憶語法sir,我的意思是'SELECT tbl_emp *,tbl_remit .remit,從tbl_emp 左tbl_report.report加入tbl_emp.ID = tbl_remit.ID ON tbl_emp.PEN = tbl_remit.PEN LEFT JOIN tbl_emp.ID = tbl_report.ID ON tbl_emp.PEN = tbl_report.PEN' – Clorae

回答

0

爲此,您可以通過連接你的其他兩個表內連接。並將結果表與emp表連接起來。爲此,您可以使用子查詢。

select * from tbl_emp x left join (
    select a.id as id, a.remit as remit,b.report as report from 
    tbl_remita,tbl_report b where a.id=b.id) y on x.id = y.id 

希望它會有所幫助。