【问题标题】:How to join get data from 2 tables and left join into 1 table in mysql如何连接从 2 个表中获取数据并在 mysql 中将数据左连接到 1 个表中
【发布时间】:2017-08-07 07:53:33
【问题描述】:

我有这张桌子

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|

无论 tbl_remit 或 tbl_report 中是否有数据,我都需要将它们全部加入 tbl_emp。

这是我使用但失败的代码。

    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   |

【问题讨论】:

  • 你加入的语法是假的。该查询真的有效吗?语法必须是from <table> join <table2> on <condition> join <table3> on <condition>
  • 对不起,我忘了输入 ON 条件,我无法正确复制或记忆语法先生,我的意思是SELECT tbl_emp*, tbl_remit.remit, tbl_report.report from tbl_emp left join 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

标签: mysql join left-join


【解决方案1】:

您可以通过使用内连接来连接其他两个表来做到这一点。并将结果表与 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

希望它会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-23
    • 2012-12-11
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2017-10-16
    相关资源
    最近更新 更多