简体   繁体   中英

How to select only first matching value from another table in MySQL?

Here is my database schema:

Payment table:

+------------+--------+--------+---------------------+
| payment_id | tab_id | amount | created             |
+------------+--------+--------+---------------------+
| 1          | 1      |  5     | 2017-05-22 12:14:27 |
| 2          | 2      |  10    | 2017-05-22 12:15:21 |
| 3          | 2      |  1     | 2017-05-22 13:11:14 |
+------------+--------+--------+---------------------+

Tab table:

+------------+----------------+
| tab_id     | service_charge |
+------------+----------------+
| 1          | 1              |
| 2          | 3              |
+------------+----------------+

I need to calculate total amounts ( amount + service_charge ) per payment, but service_charge should be included only in first payment matching tab_id .

My current query:

SELECT
  payment.payment_id,
  (payment.amount + tab.service_charge) as total_amount,
  payment.created
FROM payment
  INNER JOIN tab
    ON payment.tab_id = tab.tab_id;

Actual result:
As you can see below service_charge from tab_id = 2 included twice ( payment_id = 2 and payment_id = 3 ).

+------------+-----------------+---------------------+
| payment_id | total_amount    | created             |
+------------+-----------------+---------------------+
| 1          | 6               | 2017-05-22 12:14:27 |
| 2          | 13              | 2017-05-22 12:15:21 |
| 3          | 4               | 2017-05-22 13:11:14 |
+------------+-----------------+---------------------+  

Expected result:
total_amount should not include service_charge in payment_id = 3 as shown below.

+------------+-----------------+---------------------+
| payment_id | total_amount    | created             |
+------------+-----------------+---------------------+
| 1          | 6               | 2017-05-22 12:14:27 |
| 2          | 13              | 2017-05-22 12:15:21 |
| 3          | 1               | 2017-05-22 13:11:14 |
+------------+-----------------+---------------------+

You should determine which is the first payment matching the tab_id and then based on that info, decide if you want to use the service_charge or not:

SELECT
  payment.payment_id,
  payment.amount + if (payment.created=m.mintime, tab.service_charge, 0) as total_amount,
  payment.created
FROM payment
  INNER JOIN tab
    ON payment.tab_id = tab.tab_id
  JOIN (
    SELECT tab_id, min(created) as 'mintime'
    FROM payment
    GROUP BY tab_id
  ) AS m on m.tab_id = payment.tab_id;

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