2017-09-14 136 views
0

這裏是我的數據庫架構:如何從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 = 2service_charge包括兩次(payment_id = 2payment_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_chargepayment_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 | 
+------------+-----------------+---------------------+ 
+0

見:我爲什麼要提供MCVE對於我來說似乎是一個非常簡單的SQL查詢?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-我想成爲一個非常簡單的sql查詢) – Strawberry

+0

@Strawberry我看了一下,但它仍然不清楚這個話題可以幫助我解決我遇到的問題。 –

+0

閱讀已接受的答案(已提高106次)。遵循簡單的指示。看看會發生什麼。 – Strawberry

回答

1

您應該確定這是首付款匹配tab_id,然後根據這些信息,決定是否要使用service_charge與否:

+0

謝謝。簡單而優雅。 –

相關問題