[英]Mysql Join two tables into one output but result Subquery returns more than 1 row
I have two tables 我有两张桌子
first table is tableA: 第一个表是tableA:
+-----------+-------------+
| NIM | TA |
+-----------+-------------+
| 107032014 | A_2010/2011 |
| 107032014 | B_2010/2011 |
| 107032014 | A_2011/2012 |
| 107032014 | B_2011/2012 |
| 107032014 | A_2012/2013 |
+-----------+-------------+
and second table is tableB: 第二个表是tableB:
+-----------+---------+-------------+
| NIM | subtot | TA2 |
+-----------+---------+-------------+
| 107032014 | 6550000 | A_2010/2011 |
| 107032014 | 6550000 | B_2010/2011 |
| 107032014 | 6550000 | A_2011/2012 |
+-----------+---------+-------------+
how do I join two tables into one output like this : 我如何将两个表合并为一个输出,如下所示:
+-----------+-------------+-------------+
| 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 |
+-----------+-------------+-------------+
i used select operation : 我使用选择操作:
select *,(select subtot from tableB where NIM='107032014') as subtot from tableA where NIM='107032014';
but : 但是:
ERROR 1242 (21000): Subquery returns more than 1 row
错误1242(21000):子查询返回的行数超过1
You could use a left join
by nim
and ta
: 您可以使用
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
You can do what you want with a correlated subquery: 您可以使用相关的子查询来执行所需的操作:
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';
Because you want 0
rather than NULL
, you need a bit of extra work. 因为您想要
0
而不是NULL
,所以需要一些额外的工作。 Here is one method: 这是一种方法:
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.