我有一个由其SKU标识的产品列表。为简化起见,我在这里仅将它们命名为A,B,C,D...。默认情况下,为这些SKU中的每一个都分配了一个已经存在的GroupID,为简单起见,我在这里将其编号为1、2、3 ...相同的GroupID表示“这些SKU是等效的,因此可以使用/购买其中任何一个,因为它们没有区别”。问题是,某些SKU来自不同的购买来源会多次出现,但是由于它们来自不同的来源,因此它们具有不同的分组。因此,目标是合并分组并确保它们具有相同的分组。如果我的插图可能不是很漂亮,我已经表示歉意,但是我正在尝试。这是一个有关原始数据外观的小数据表示例(第一行是列名称): Source SKU GroupID Seller1 A 1 Seller1 B 1 Seller1 C 1 Seller2 B 2 Seller2 D 2 Seller2 E 2 Seller3 A 3 Seller3 B 3 Seller4 F 4 Seller4 G 4 Seller4 H 4结果应为: Source SKU GroupID Seller1 A 1 Seller1 B 1 Seller1 C 1 Seller2 B 1 Seller2 D 1 Seller2 E 1 Seller3 A 1 Seller3 B 1 Seller4 F 4 Seller4 G 4 Seller4 H 4基本上是Any SKU in GroupID X is a subset of GroupID Y, then GroupID Y = GroupID X。但这应该应用于所有GroupID,因此它似乎是递归的。我希望我可以展示已经尝试过并且已经尝试了几天的代码,但是实际上我只能产生垃圾。在C#中,我知道如何处理此问题,但是由于经验不足,我似乎无法全神贯注地使用SQL,不幸的是,我在SQL中需要使用此方法。我将非常感谢您提供的任何帮助,即使这只是您建议我尝试的提示或指导。非常感谢! 最佳答案 您需要组之间的对应关系,您可以使用递归CTE进行计算:with recursive tt as ( select distinct t1.groupid as groupid1, t2.groupid as groupid2 from t t1 join t t2 on t1.sku = t2.sku ), cte as ( select tt.groupid1, tt.groupid2, concat_ws(',', tt.groupid1, tt.groupid2) as visited from tt union all select cte.groupid1, tt.groupid2, concat_ws(',', visited, tt.groupid2) from cte join tt on cte.groupid2 = tt.groupid1 where find_in_set(tt.groupid2, cte.visited) = 0 )select groupid1, min(groupid2) as overall_groupfrom ctegroup by groupid1;然后,您可以将其重新连接到原始表以获取“总体组”:with recursive tt as ( select distinct t1.groupid as groupid1, t2.groupid as groupid2 from t t1 join t t2 on t1.sku = t2.sku ), cte as ( select tt.groupid1, tt.groupid2, concat_ws(',', tt.groupid1, tt.groupid2) as visited from tt union all select cte.groupid1, tt.groupid2, concat_ws(',', visited, tt.groupid2) from cte join tt on cte.groupid2 = tt.groupid1 where find_in_set(tt.groupid2, cte.visited) = 0 )select t.*, g.overall_groupfrom t join (select groupid1, min(groupid2) as overall_group from cte group by groupid1 ) g on t.groupid = g.groupid1;Here是db 小提琴。注意:您的示例数据相当“完整”,因此您无需为该特定数据提供递归CTE。但是,我猜测您的真实组的重叠较少,在这种情况下,必须进行递归。关于mysql - 如何在SQL中(递归)确定等效分组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57470236/
10-16 13:31