(MySQL)2个外键引用同一张表

时间:2019-11-13 13:28:34

标签: mysql

表上交易c_accd_acc基于account.id

如何获得如下所示的查询结果?

结果表中的借方和贷方会根据其在表交易中的帐户类型自动汇总,无论是借方帐户还是贷方帐户。我当时想过两个联接account aaccount b,但是我不知道如何实现它。我需要帮助。谢谢!

表名:帐户

+---------------------------+
|ID | account               |
|---+-----------------------|
|101| cash                  |
|---+-----------------------|
|102| accounts receivable   |
|---+-----------------------|
|103| notes receivable      |
|---+-----------------------|
|104| interest receivable   |
|---+-----------------------|
|105| merchandise inventory |
|---+-----------------------|
|201| accounts payable      |
+---------------------------+

表名:交易

+-----------------------------+
|ID|d_acc|c_acc|debit|credit  |
|--+-----+-----+-----+--------|
|1 |101  |102  |10000|10000   |
|--+-----+-----+-----+--------|
|2 |201  |101  |1000 |1000    |
|--+-----+-----+-----+--------|
|3 |101  |102  |300  |300     |
+-----------------------------+

查询结果

+-----------------------------------+
|Account              |Debit|Credit |
|---------------------+-----+-------|
|Cash                 |10300|1000   |
|---------------------+-----+-------|
|accounts receivable  |     |10300  |
|---------------------+-----+-------|
|notes receivable     |     |       |
|---------------------+-----+-------|
|interest receivable  |     |       |
|---------------------+-----+-------|
|merchandise inventory|     |       |
|---------------------+-----+-------|
|accounts payable     |1000 |10000  |
+-----------------------------------+

1 个答案:

答案 0 :(得分:2)

您可以合并2个查询并将结果分组如下:

SELECT
x.account,
SUM(x.debit) AS debit,
SUM(x.credit) AS credit
FROM
(

SELECT
`accounts`.`account`,
`transaction`.`debit`,
0 AS `credit`
FROM
`accounts`
LEFT JOIN `transaction` ON (`accounts`.`ID`=`transaction`.`d_acc`)

UNION

SELECT
`accounts`.`account`,
0 AS `debit`,
`transaction`.`credit`
FROM
`accounts`
LEFT JOIN `transaction` ON (`accounts`.`ID`=`transaction`.`c_acc`)

) x
GROUP BY account

注意:我添加了反引号,因为“交易”是保留关键字