简体   繁体   English

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

[英](MySQL) 2 foreign keys referencing the same table

On table transaction c_acc and d_acc are based on account.id表上的事务c_accd_acc基于account.id

How can I achieve the query result as shown below?我怎样才能达到如下所示的查询结果?

The debit and credit in results table is auto summed up based on their type of account in table transaction, whether it's debit account or credit account.结果表中的借方和贷方是根据它们在表交易中的账户类型自动汇总的,无论是借方账户还是贷方账户。 I was thinking of two joins account a and account b But I dont know how to implement it.我在想两个加入account aaccount b但我不知道如何实现它。 I need help.我需要帮助。 Thank you!谢谢!

Table name: accounts表名:accounts

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

Table name: transaction表名:事务

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

Query result查询结果

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

You can union 2 queries and group the results like this:您可以联合 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

Note: I added backticks because 'transaction' is a reserved keyword注意:我添加了反引号,因为“事务”是保留关键字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM