【问题标题】:Mysql Join two tables into one output but result Subquery returns more than 1 rowMysql将两个表连接成一个输出但结果子查询返回超过1行
【发布时间】:2018-05-08 14:03:08
【问题描述】:

我有两张桌子

第一个表是表A:

+-----------+-------------+
| NIM       | TA          |
+-----------+-------------+
| 107032014 | A_2010/2011 |
| 107032014 | B_2010/2011 |
| 107032014 | A_2011/2012 |
| 107032014 | B_2011/2012 |
| 107032014 | A_2012/2013 |
+-----------+-------------+

第二个表是tableB:

+-----------+---------+-------------+
| 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           |
+-----------+-------------+-------------+

我使用了选择操作:
select *,(select subtot from tableB where NIM='107032014') as subtot from tableA where NIM='107032014';
但是:

ERROR 1242 (21000):子查询返回多于 1 行

【问题讨论】:

标签: mysql sql join


【解决方案1】:

您可以通过nim 和ta 使用left join:

SELECT    a.nim, a.ta, COALESCE(subtot, 0)
FROM      tablea a
LEFT JOIN tableb b ON a.nim = b.nim AND a.ta = b.ta

【讨论】:

    【解决方案2】:

    您可以使用相关子查询做您想做的事:

    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';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多