连接两个表并仅在两个或多个记录具有相同值时分组

时间:2018-07-27 06:25:21

标签: mysql relational-database

我有2张桌子:

manifests
id | customer | paid_order | price | payment_method

paid_orders
id | paid

JOIN paid_orders ON manifests.paid_order = paid_order_id
  

让我们假设这种情况:
  有2个相同的customer但有不同的payment_method

customer | paid_order | price | payment_method |  paid  |
    1    |      1     | 200   |        0       |  200   |
    1    |     NULL   | 100   |        1       |  NULL  |
    2    |     NULL   | 150   |        1       |  NULL  |

如果有两个相同的客户,我只想GROUP BY customer,也想 PICK ,只选择payment_method中的0

预期结果:

customer | paid_order | price | payment_method |  paid  |
    1    |      1     | 200   |        0       |  200   |
    2    |     NULL   | 150   |        1       |  NULL  |

1 个答案:

答案 0 :(得分:1)

一种方法是始终从payment_method最小值的一个或多个客户记录中选择记录:

SELECT m1.*
FROM manifest m1
INNER JOIN
(
    SELECT customer, MIN(payment_method) AS min_payment_method
    FROM manifest
    GROUP BY customer
) m2
    ON m1.customer = m2.customer AND m1.payment_method = m2.min_payment_method;

该逻辑应该起作用,因为如果存在payment_method为零,则该记录将成为目标。否则,将定位一个价值记录。