[英]Mysql Join two tables into one output but result Subquery returns more than 1 row
我有两张桌子
第一个表是tableA:
+-----------+-------------+
| 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';
但是:
错误1242(21000):子查询返回的行数超过1
您可以使用nim
和ta
的left join
nim
:
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
您可以使用相关的子查询来执行所需的操作:
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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.