Fix error judgement for MainFragmentLocatedRegion and MostlyUsedDataRegion in distributed plan

diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/distribution/ExchangeNodeAdder.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/distribution/ExchangeNodeAdder.java
index 79d9f6b..e95aa68 100644
--- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/distribution/ExchangeNodeAdder.java
+++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/distribution/ExchangeNodeAdder.java
@@ -462,24 +462,29 @@
     // Step 2: return the RegionReplicaSet with max node count
     long maxCount = -1;
     TRegionReplicaSet result = DataPartition.NOT_ASSIGNED;
-    for (Map.Entry<TRegionReplicaSet, Long> entry : groupByRegion.entrySet()) {
-      TRegionReplicaSet region = entry.getKey();
-      if (DataPartition.NOT_ASSIGNED.equals(region)) {
-        continue;
-      }
-      if (region.equals(context.queryContext.getMainFragmentLocatedRegion())) {
-        return context.queryContext.getMainFragmentLocatedRegion();
-      }
-      if (region.equals(context.getMostlyUsedDataRegion())) {
-        return region;
-      }
-      long planNodeCount = entry.getValue();
-      if (planNodeCount > maxCount) {
-        maxCount = planNodeCount;
-        result = region;
-      } else if (planNodeCount == maxCount
-          && region.getRegionId().getId() < result.getRegionId().getId()) {
-        result = region;
+    // use MainFragmentLocatedRegion firstly,
+    // if MainFragmentLocatedRegion is not exist, use MostlyUsedDataRegion,
+    // otherwise use region which has most plan nodes.
+    if (context.queryContext.getMainFragmentLocatedRegion() != null
+        && groupByRegion.containsKey(context.queryContext.getMainFragmentLocatedRegion())) {
+      return context.queryContext.getMainFragmentLocatedRegion();
+    } else if (context.getMostlyUsedDataRegion() != null
+        && groupByRegion.containsKey(context.getMostlyUsedDataRegion())) {
+      return context.getMostlyUsedDataRegion();
+    } else {
+      for (Map.Entry<TRegionReplicaSet, Long> entry : groupByRegion.entrySet()) {
+        TRegionReplicaSet region = entry.getKey();
+        if (DataPartition.NOT_ASSIGNED.equals(region)) {
+          continue;
+        }
+        long planNodeCount = entry.getValue();
+        if (planNodeCount > maxCount) {
+          maxCount = planNodeCount;
+          result = region;
+        } else if (planNodeCount == maxCount
+            && region.getRegionId().getId() < result.getRegionId().getId()) {
+          result = region;
+        }
       }
     }
     return result;