如何使用JOIN管理来自3个不同表的SELECT数据?

时间:2019-06-03 00:54:02

标签: php mysql sql

我有3个不同的桌子。

  1. 驱动程序
| id  | name |
|-----|------|
| 10  | abc  |
| 21  | xyz  |
  1. 预订
| id | driver_id | booking_amount |
|----|-----------|----------------|
| 1  | 10        |  250           |
| 2  | 10        |  150           |
| 3  | 21        |  200           |
| 4  | 21        |  300           |
  1. 收入
| id | driver_id | credit | debit |   date   |
|----|-----------|--------|-------|----------|
| 1  | 10        | 100    |       | 1-1-2019 |
| 2  | 10        | 250    |       | 2-1-2019 |
| 3  | 10        |        | 200   | 3-1-2019 |
| 4  | 21        | 250    |       | 1-1-2019 |
| 5  | 21        | 400    |       | 2-1-2019 |
| 6  | 21        |        | 50    | 3-1-2019 |
  • driver.id = booking.driver_id
  • driver.id = income.driver_id

我已使用此查询>>

SELECT driver.*, sum(booking.total_booking_income) as total_income 
FROM driver
JOIN booking ON driver.id=booking.driver_id
GROUP BY driver.id
ORDER BY driver.id DESC

注意:但是我无法在此查询中添加余额字段。

我想在预订组和收入组之后按驾驶员ID记录所有驾驶员收入记录

| id | driver_id | driver_name | total_income | balance |
|----|-----------|-------------|--------------|---------|
| 1  | 10        | abc         | 400          | -250    | 
| 2  | 21        | xyz         | 500          | 100     |

1 个答案:

答案 0 :(得分:1)

假设余额是贷方与借方之差,则:

SELECT d.*, sum(b.total_booking_income) as total_income,
       i.balance
FROM driver d JOIN
     booking b
     ON d.id = b.driver_id LEFT JOIN
     (SELECT i.driver_id,
             SUM(i.credit) - SUM(i.debit) as balance
      FROM income i
      GROUP BY i.driver_id
     ) i
     ON i.driver_id = d.id
GROUP BY d.id, i.balance
ORDER BY d.id DESC;