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

问题描述 投票:1回答:1

在表上交易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  |
+-----------------------------------+
mysql
1个回答
1
投票

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

SELECT
account,
sum(debit) AS debit,
sum(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

注意:我添加了反引号,因为'transaction'是保留关键字

© www.soinside.com 2019 - 2024. All rights reserved.