這裏是我的數據庫架構:如何從MySQL中的另一個表中只選擇第一個匹配值?
付款表:
+------------+--------+--------+---------------------+
| 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_id | service_charge |
+------------+----------------+
| 1 | 1 |
| 2 | 3 |
+------------+----------------+
我需要計算每支付總金額(amount
+ service_charge
),但service_charge
應僅包含在匹配tab_id
的第一筆付款中。
我當前的查詢:
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;
實際結果:
正如你可以看到下面從tab_id = 2
service_charge
包括兩次(payment_id = 2
和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 |
+------------+-----------------+---------------------+
預期結果:如下所示
total_amount
不應包括在service_charge
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 | 1 | 2017-05-22 13:11:14 |
+------------+-----------------+---------------------+
見:我爲什麼要提供MCVE對於我來說似乎是一個非常簡單的SQL查詢?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-我想成爲一個非常簡單的sql查詢) – Strawberry
@Strawberry我看了一下,但它仍然不清楚這個話題可以幫助我解決我遇到的問題。 –
閱讀已接受的答案(已提高106次)。遵循簡單的指示。看看會發生什麼。 – Strawberry