简体   繁体   中英

select data from multiple tables with join group by, in one mysql query

table-1 Bill

| bill_id| date      | supplier_id |amount|
| 101    | 2019-03-16| 1570        |1000  |
| 102    | 2019-05-20| 1570        |2500  |

table-2 payment

| bill_id| date       | paid|
| 101    | 2019-03-17 | 800   |
| 101    | 2019-05-20 | 150   |

Expected result

| supplier_id |bill_id |amount|Paid | Balance|
| 1570        | 101    |1000  | 950 | 50     |
| 1570        | 102    |2500  | 0   | 2500   |

how do i achieve this

I would pre-aggregate payment

SELECT p.bill_id
     , SUM(p.amount) AS paid
  FROM payment p 
 GROUP BY p.bill_id

Then use that query as an inline view ...

SELECT b.supplier_id
     , b.bill_id
     , b.amount
     , IFNULL(q.paid,0)            AS paid 
     , b.amount - IFNULL(q.paid.0) AS balance  
  FROM bill b
  LEFT
  JOIN ( SELECT p.bill_id
              , SUM(p.amount) AS paid
           FROM payment p 
          GROUP BY p.bill_id
       ) q
    ON q.bill_id = b.bill_id
 ORDER
    BY b.supplier_id
     , b.bill_id

Note that we aren't given any guarantee about uniqueness of bill_id in bill table. It looks like it might be the primary key, but that's just a guess. If that's not unique, then the results from this query are likely not going to be what we want.

Notice that we are using an outer join (the LEFT keyword) so the query will return rows for bill for which there are no matching rows in payment . The IFNULL wrapper is shorthand way of converting a NULL value (which we would get if there isn't a matching row in payment) into a zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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