如何使用单个查询合并两个表

时间:2018-08-07 07:00:44

标签: mysql

我有三个表,分别称为收据,receivedetet。收据表存储收据信息的记录,而收款人将费用明细存储在该收据中。
餐桌收据:

receiptno |付款人|数量

66 | 333 | 1600
67 | 332 | 1500
68 | 215 | 300

表收据:

receiptno |费用|数量

66 | 21 | 50
66 | 33 | 50
66 | 55 | 1500
67 | 55 | 1500
68 | 12 | 100
68 | 44 | 100
68 | 22 | 100

餐桌费:

Id |代码没事

12 | Xbre | 0
21 |下降| 0
22 |抗议0
33 |烫发| 0
44 | Afee | 0
55 | TFee | 1

如果“ INASSESS”字段为0或1并且“ RECEIPDET”上的“总金额”表求和,我希望查询将基于所选字段显示记录。

DESIRED OUTPUT  

receiptno |付款人| SUM(receiptdet.amount)|没钱
66 | 333 | 1500 | 1
67 | 332 | 1500 | 1

OR

receiptno |付款人| SUM(receiptdet.amount)|没事

66 | 333 | 100 | 0
68 | 215 | 300 | 0

到目前为止,我必须对两个表进行单独的查询。如果有人可以帮助我,我希望将其作为一个查询,我将不胜感激。预先感谢

SELECT
    receipt.receiptno,
    receipt.amount
FROM
    receipt ORDER
BY LENGTH(receipt.receiptno), receipt.receiptno

SELECT
    Sum(receiptdet.amount),
    receiptdet.student,
    feetype.inassess,
    receiptdet.receiptno
FROM
    receiptdet
    Left Join fees ON receiptdet.fee = fees.id
    Left Join feetype ON fees.feetype = feetype.id
WHERE
    feetype.inassess =  '0' AND
    receiptdet.receiptno =  '66'

1 个答案:

答案 0 :(得分:3)

您可以使用JOINs通过它们的链接列将所有表放在一起,然后使用GROUP BY根据receiptnoinassess对数据进行分组。一个查询将为您提供所需的所有数据:

SELECT r.receiptno, r.payor, SUM(rd.amount) AS fees, f.inassess
FROM receipt r
LEFT JOIN receiptdet rd ON rd.receiptno = r.receiptno
JOIN fees f ON f.id = rd.fee
GROUP BY f.inassess, r.receiptno

对于您的示例数据,它给出:

receiptno   payor   fees    inassess
66          333     100     0
68          215     300     0
66          333     1500    1
67          332     1500    1

SQLFiddle