gpt4 book ai didi

mysql - 仅当两个或多个记录具有相同值时才连接两个表并分组

转载 作者:行者123 更新时间:2023-11-29 10:07:51 25 4
gpt4 key购买 nike

我有 2 张 table :

manifests
id | customer | paid_order | price | payment_method

paid_orders
id | paid

JOIN paid_orders ON manifests.paid_order = paid_order_id

Let's assume this scenario:
There are 2 same customer but has different 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而且还选择payment_method0 如果有两个相同的客户。

预期结果:

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

最佳答案

一种方法是始终从一个或可能多个客户记录中选择 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 ,则该记录将成为目标。否则,单值记录将成为目标。

关于mysql - 仅当两个或多个记录具有相同值时才连接两个表并分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51551933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com