From 6f0d69e031da100b422ae3367780f02d21427451 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@2ndquadrant.com>
Date: Mon, 17 Jun 2024 16:59:04 +0200
Subject: [PATCH v20240617 48/56] Add fastpath when combine the 2 MCV like
 eqjoinsel_inner.

when MCV2 exactly matches clauses.
---
 src/backend/statistics/mcv.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)

diff --git a/src/backend/statistics/mcv.c b/src/backend/statistics/mcv.c
index e1c5abf3148..4eec6592562 100644
--- a/src/backend/statistics/mcv.c
+++ b/src/backend/statistics/mcv.c
@@ -2507,13 +2507,6 @@ mcv_combine_extended(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2,
 			if (cmatches2 && !cmatches2[j])
 				continue;
 
-			/*
-			 * XXX We can't skip based on existing matches2 value, because
-			 * there may be duplicates in the first MCV.
-			 *
-			 * From Andy: what does this mean?
-			 */
-
 			/*
 			 * Evaluate if all the join clauses match between the two MCV
 			 * items.
@@ -2564,6 +2557,14 @@ mcv_combine_extended(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2,
 				/* XXX Do we need to do something about base frequency? */
 				matches1[i] = matches2[j] = true;
 				s += mcv1->items[i].frequency * mcv2->items[j].frequency;
+				nmatches += 1;
+
+				if (mcv2->ndimensions == list_length(clauses))
+					/*
+					 * no more items in mcv2 could match mcv1[i] in this case,
+					 * so break fast.
+					 */
+					break;
 			}
 		}
 	}
-- 
2.45.2

