[英]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.