Mysql将两个表连接到一个输出中,但结果子查询返回多行

Mysql将两个表连接到一个输出中,但结果子查询返回多行,mysql,sql,join,Mysql,Sql,Join,我有两张桌子 第一个表是表A: +-----------+-------------+ | NIM | TA | +-----------+-------------+ | 107032014 | A_2010/2011 | | 107032014 | B_2010/2011 | | 107032014 | A_2011/2012 | | 107032014 | B_2011/2012 | | 107032014 | A_2012/2013 | +---------

我有两张桌子

第一个表是表A:

+-----------+-------------+
| NIM       | TA          |
+-----------+-------------+
| 107032014 | A_2010/2011 |
| 107032014 | B_2010/2011 |
| 107032014 | A_2011/2012 |
| 107032014 | B_2011/2012 |
| 107032014 | A_2012/2013 |
+-----------+-------------+
第二个表是表B:

+-----------+---------+-------------+
| NIM       | subtot  |     TA2     |
+-----------+---------+-------------+
| 107032014 | 6550000 | A_2010/2011 |
| 107032014 | 6550000 | B_2010/2011 |
| 107032014 | 6550000 | A_2011/2012 |
+-----------+---------+-------------+
如何将两个表连接到一个输出中,如下所示:

+-----------+-------------+-------------+
| NIM       | TA          | subtot      |
+-----------+-------------+-------------+
| 107032014 | A_2010/2011 | 6550000     |
| 107032014 | B_2010/2011 | 6550000     |
| 107032014 | A_2011/2012 | 6550000     |
| 107032014 | B_2011/2012 | 0           |
| 107032014 | A_2012/2013 | 0           |
+-----------+-------------+-------------+
我使用了选择操作: 选择*,从NIM='107032014'的表格B中选择小计,作为NIM='107032014'的表格A中的小计; 但是:

错误1242 21000:子查询返回的行数超过1行


可以使用相关子查询执行所需操作:

select a.*,
       (select subtot
        from tableB b
        where b.NIM = a.NIM and
              b.TA2 = a.TA
       ) as subtot
from tableA a
where a.NIM = '107032014';
因为您想要0而不是NULL,所以需要做一些额外的工作。这里有一种方法:

select a.*,
       (select coalesce(sum(subtot), 0)
        from tableB b
        where b.NIM = a.NIM and
              b.TA2 = a.TA
       ) as subtot
from tableA a
where a.NIM = '107032014';

可以使用相关子查询执行所需操作:

select a.*,
       (select subtot
        from tableB b
        where b.NIM = a.NIM and
              b.TA2 = a.TA
       ) as subtot
from tableA a
where a.NIM = '107032014';
因为您想要0而不是NULL,所以需要做一些额外的工作。这里有一种方法:

select a.*,
       (select coalesce(sum(subtot), 0)
        from tableB b
        where b.NIM = a.NIM and
              b.TA2 = a.TA
       ) as subtot
from tableA a
where a.NIM = '107032014';
您可以使用nim和ta的左连接:

您可以使用nim和ta的左连接:

寻找加入…寻找加入。。。