如何从主表的2个子表中的任何一个获取名称?

时间:2018-03-12 12:11:53

标签: mysql

我有3个表格,数据如下。我能够对AccountID的交易进行求和,但也希望获得来自2个表中任何一个的帐户名称

Transactions: (Type 1=Credit, 2=Debit)
+------------+------+--------+
| AccountID  | Type | Amount |
+------------+------+--------+
| 1000038038 |  1   |  2.15  |
| 1000038038 |  2   |  1.75  |
| 1000038040 |  1   |  1.37  |
| 1000038040 |  2   |  4.82  |
| 1000038040 |  1   |  1.09  |
| 1000038042 |  1   |  5.34  |
| 1000038042 |  2   |  2.43  |
| 1000038060 |  1   |  2.55  |
| 1000038065 |  1   |  3.00  |
+------------+------+--------+

Customers1:
+------------+---------------+
| AccountID  | Name          |
+------------+---------------+
| 1000038038 | Bob           |
| 1000038040 | Jason         |
+------------+---------------+

Customers2:
+------------+---------------+
| AccountID  | Name          |
+------------+---------------+
| 1000038042 | Vince         |
| 1000038060 | Craig         |
+------------+---------------+

现在,通过以下查询,我可以很好地完成余额......

SELECT AccountID,
   SUM(COALESCE(CASE WHEN Type=1 THEN Amount END,0)) - 
   SUM(COALESCE(CASE WHEN Type=2 THEN Amount END,0)) AS Balance 
FROM `Transactions`
GROUP BY AccountID ASC
ORDER BY AccountID

上述查询将结果返回为...

+------------+---------+
| AccountID  | Balance |
+------------+---------+
| 1000038038 | 0.40    |
| 1000038040 | -2.36   |
| 1000038042 | 2.91    |
| 1000038060 | 2.55    |
| 1000038065 | 3.00    |
+------------+---------+

我想要的是还包括来自以下两个客户表中的任何一个的名称......(注意:a / c 38065是一个孤儿,所以它没有与之相关的名称客户表)

+------------+---------+---------+
| AccountID  | Name    | Balance |
+------------+---------+---------+
| 1000038038 | Bob     | 0.40    |
| 1000038040 | Jason   | -2.36   |
| 1000038042 | Vince   | 2.91    |
| 1000038060 | Craig   | 2.55    |
| 1000038065 |         | 3.00    |
+------------+---------+---------+

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT
   AccountID,
   IFNULL(B.Name, C.Name) AS Name,
   SUM(COALESCE(CASE WHEN A.Type=1 THEN Amount END,0)) - 
   SUM(COALESCE(CASE WHEN A.Type=2 THEN Amount END,0)) AS Balance 
FROM `Transactions` A 
LEFT JOIN Customers1 B ON A.AccountID=B.AccountID  
LEFT JOIN Customers2 C ON A.AccountID=C.AccountID
GROUP BY A.AccountID 
ORDER BY A.AccountID ASC;

请参阅MySQL Join Made Easy以及如何使用MySQL IFNULL function进行洞察。