diff --git a/CRM/Contact/BAO/Query.php b/CRM/Contact/BAO/Query.php
index cdde954b26e77b95dece6dfe61a667c7f40d4dff..24944a78a5cc0239b4766f3e8ea30eba06d52594 100644
--- a/CRM/Contact/BAO/Query.php
+++ b/CRM/Contact/BAO/Query.php
@@ -5791,7 +5791,7 @@ INNER JOIN civicrm_relationship displayRelType ON ( displayRelType.contact_id_a
 INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRelType.contact_id_a OR transform_temp.contact_id = displayRelType.contact_id_b )
 ";
         $qcache['where'] = "
-AND displayRelType.relationship_type_id = {$this->_displayRelationshipType}
+WHERE displayRelType.relationship_type_id = {$this->_displayRelationshipType}
 AND   displayRelType.is_active = 1
 ";
       }
@@ -5812,7 +5812,7 @@ INNER JOIN $tableName transform_temp ON ( transform_temp.contact_id = displayRel
 ";
         }
         $qcache['where'] = "
-AND displayRelType.relationship_type_id = $relType
+WHERE displayRelType.relationship_type_id = $relType
 AND   displayRelType.is_active = 1
 ";
       }
@@ -5836,14 +5836,10 @@ AND   displayRelType.is_active = 1
       else {
         $from .= $qcache['from'];
       }
-      if (!strlen($where)) {
-        $where = " WHERE 1 ";
-      }
-      $where .= $qcache['where'];
+      $where = $qcache['where'];
       if (!empty($this->_tables['civicrm_case'])) {
         // Change the join on CiviCRM case so that it joins on the right contac from the relationship.
         $from = str_replace("ON civicrm_case_contact.contact_id = contact_a.id", "ON civicrm_case_contact.contact_id = transform_temp.contact_id", $from);
-        $where = str_replace("AND civicrm_case_contact.contact_id = contact_a.id", "AND civicrm_case_contact.contact_id = transform_temp.contact_id", $where);
         $where .= " AND displayRelType.case_id = civicrm_case_contact.case_id ";
       }
       if (!empty($this->_permissionFromClause) && !stripos($from, 'aclContactCache')) {
diff --git a/tests/phpunit/CRM/Case/BAO/QueryTest.php b/tests/phpunit/CRM/Case/BAO/QueryTest.php
index 87fc0e344d6f5cba996c27eeaf6c5ee6a48863f5..54f83a133a5f74ad6bd9bcaa4aae6fd592af80b8 100644
--- a/tests/phpunit/CRM/Case/BAO/QueryTest.php
+++ b/tests/phpunit/CRM/Case/BAO/QueryTest.php
@@ -139,16 +139,16 @@ class CRM_Case_BAO_QueryTest extends CiviCaseTestCase {
    *
    * @throws \Exception
    */
-  public function testAdvancedSearchWithDisplayRelationshipsAndCaseType() {
-    // Preperation
-    $benefitRelationshipTypeId = civicrm_api3('RelationshipType', 'getvalue', ['return' => 'id', 'name_a_b' => 'Benefits Specialist is']);
+  public function testAdvancedSearchWithDisplayRelationshipsAndCaseType(): void {
+    $this->markTestIncomplete('temporarily disabled as https://github.com/civicrm/civicrm-core/pull/20002 reverted for now');
+    $benefitRelationshipTypeId = $this->callAPISuccess('RelationshipType', 'getvalue', ['return' => 'id', 'name_a_b' => 'Benefits Specialist is']);
     $clientContactID = $this->individualCreate(['first_name' => 'John', 'last_name' => 'Smith']);
     $benefitSpecialist1 = $this->individualCreate(['Individual', 'first_name' => 'Alexa', 'last_name' => 'Clarke']);
     $benefitSpecialist2 = $this->individualCreate(['Individual', 'first_name' => 'Sandra', 'last_name' => 'Johnson']);
     $housingSupportCase = $this->createCase($clientContactID, NULL, ['case_type' => 'housing_support', 'case_type_id' => 1]);
     $adultDayCareReferralCase = $this->createCase($clientContactID, NULL, ['case_type' => 'adult_day_care_referral', 'case_type_id' => 2]);
-    civicrm_api3('Relationship', 'create', ['contact_id_a' => $clientContactID, 'contact_id_b' => $benefitSpecialist1, 'relationship_type_id' => $benefitRelationshipTypeId, 'case_id' => $housingSupportCase->id]);
-    civicrm_api3('Relationship', 'create', ['contact_id_a' => $clientContactID, 'contact_id_b' => $benefitSpecialist2, 'relationship_type_id' => $benefitRelationshipTypeId, 'case_id' => $adultDayCareReferralCase->id]);
+    $this->callAPISuccess('Relationship', 'create', ['contact_id_a' => $clientContactID, 'contact_id_b' => $benefitSpecialist1, 'relationship_type_id' => $benefitRelationshipTypeId, 'case_id' => $housingSupportCase->id]);
+    $this->callAPISuccess('Relationship', 'create', ['contact_id_a' => $clientContactID, 'contact_id_b' => $benefitSpecialist2, 'relationship_type_id' => $benefitRelationshipTypeId, 'case_id' => $adultDayCareReferralCase->id]);
 
     // Search setup
     $formValues = ['display_relationship_type' => $benefitRelationshipTypeId . '_b_a', 'case_type_id' => 1];
diff --git a/tests/phpunit/CRM/Contact/BAO/QueryTest.php b/tests/phpunit/CRM/Contact/BAO/QueryTest.php
index da05aa6b1549c653afa65020302230e487861d2b..2147bb609ad33fe3c4119b9088fa5d4aca4bedc8 100644
--- a/tests/phpunit/CRM/Contact/BAO/QueryTest.php
+++ b/tests/phpunit/CRM/Contact/BAO/QueryTest.php
@@ -1317,4 +1317,53 @@ civicrm_relationship.is_active = 1 AND
     $this->assertEquals('World Region = Middle East and North Africa', $query->_qill[0][0]);
   }
 
+  /**
+   * Tests the advanced search query by searching on related contacts and contact type same time.
+   *
+   * Preparation:
+   *   Create an individual contact Contact A
+   *   Create an organization contact Contact B
+   *   Create an "Employer of" relationship between them.
+   *
+   * Searching:
+   *   Go to advanced search
+   *   Click on View contact as related contact
+   *   Select Employee of as relationship type
+   *   Select "Organization" as contact type
+   *
+   * Expected results
+   *   We expect to find contact A.
+   *
+   * @throws \Exception
+   */
+  public function testAdvancedSearchWithDisplayRelationshipsAndContactType(): void {
+    $employeeRelationshipTypeId = $this->callAPISuccess('RelationshipType', 'getvalue', ['return' => 'id', 'name_a_b' => 'Employee of']);
+    $indContactID = $this->individualCreate(['first_name' => 'John', 'last_name' => 'Smith']);
+    $orgContactID = $this->organizationCreate(['contact_type' => 'Organization', 'organization_name' => 'Healthy Planet Fund']);
+    $this->callAPISuccess('Relationship', 'create', ['contact_id_a' => $indContactID, 'contact_id_b' => $orgContactID, 'relationship_type_id' => $employeeRelationshipTypeId]);
+
+    // Search setup
+    $formValues = ['display_relationship_type' => $employeeRelationshipTypeId . '_a_b', 'contact_type' => 'Organization'];
+    $params = CRM_Contact_BAO_Query::convertFormValues($formValues, 0, FALSE, NULL, []);
+    $isDeleted = FALSE;
+    $selector = new CRM_Contact_Selector(
+      'CRM_Contact_Selector',
+      $formValues,
+      $params,
+      NULL,
+      CRM_Core_Action::NONE,
+      NULL,
+      FALSE,
+      'advanced'
+    );
+    $queryObject = $selector->getQueryObject();
+    $sql = $queryObject->query(FALSE, FALSE, FALSE, $isDeleted);
+    // Run the search
+    $rows = CRM_Core_DAO::executeQuery(implode(' ', $sql))->fetchAll();
+    // Check expected results.
+    $this->assertCount(1, $rows);
+    $this->assertEquals('John', $rows[0]['first_name']);
+    $this->assertEquals('Smith', $rows[0]['last_name']);
+  }
+
 }
diff --git a/tests/phpunit/CRM/Contact/SelectorTest.php b/tests/phpunit/CRM/Contact/SelectorTest.php
index 2841d6f1f4510b33284b2e53c3d4abecae039606..ef8a9946193cbbaccc4f91fe8e67250a967a579f 100644
--- a/tests/phpunit/CRM/Contact/SelectorTest.php
+++ b/tests/phpunit/CRM/Contact/SelectorTest.php
@@ -470,7 +470,7 @@ class CRM_Contact_SelectorTest extends CiviUnitTestCase {
           'searchDescendentGroups' => FALSE,
           'expected_query' => [
             0 => 'SELECT contact_a.id as contact_id, contact_a.contact_type as `contact_type`, contact_a.contact_sub_type as `contact_sub_type`, contact_a.sort_name as `sort_name`, contact_a.display_name as `display_name`, contact_a.do_not_email as `do_not_email`, contact_a.do_not_phone as `do_not_phone`, contact_a.do_not_mail as `do_not_mail`, contact_a.do_not_sms as `do_not_sms`, contact_a.do_not_trade as `do_not_trade`, contact_a.is_opt_out as `is_opt_out`, contact_a.legal_identifier as `legal_identifier`, contact_a.external_identifier as `external_identifier`, contact_a.nick_name as `nick_name`, contact_a.legal_name as `legal_name`, contact_a.image_URL as `image_URL`, contact_a.preferred_communication_method as `preferred_communication_method`, contact_a.preferred_language as `preferred_language`, contact_a.preferred_mail_format as `preferred_mail_format`, contact_a.first_name as `first_name`, contact_a.middle_name as `middle_name`, contact_a.last_name as `last_name`, contact_a.prefix_id as `prefix_id`, contact_a.suffix_id as `suffix_id`, contact_a.formal_title as `formal_title`, contact_a.communication_style_id as `communication_style_id`, contact_a.job_title as `job_title`, contact_a.gender_id as `gender_id`, contact_a.birth_date as `birth_date`, contact_a.is_deceased as `is_deceased`, contact_a.deceased_date as `deceased_date`, contact_a.household_name as `household_name`, IF ( contact_a.contact_type = \'Individual\', NULL, contact_a.organization_name ) as organization_name, contact_a.sic_code as `sic_code`, contact_a.is_deleted as `contact_is_deleted`, IF ( contact_a.contact_type = \'Individual\', contact_a.organization_name, NULL ) as current_employer, civicrm_address.id as address_id, civicrm_address.street_address as `street_address`, civicrm_address.supplemental_address_1 as `supplemental_address_1`, civicrm_address.supplemental_address_2 as `supplemental_address_2`, civicrm_address.supplemental_address_3 as `supplemental_address_3`, civicrm_address.city as `city`, civicrm_address.postal_code_suffix as `postal_code_suffix`, civicrm_address.postal_code as `postal_code`, civicrm_address.geo_code_1 as `geo_code_1`, civicrm_address.geo_code_2 as `geo_code_2`, civicrm_address.state_province_id as state_province_id, civicrm_address.country_id as country_id, civicrm_phone.id as phone_id, civicrm_phone.phone_type_id as phone_type_id, civicrm_phone.phone as `phone`, civicrm_email.id as email_id, civicrm_email.email as `email`, civicrm_email.on_hold as `on_hold`, civicrm_im.id as im_id, civicrm_im.provider_id as provider_id, civicrm_im.name as `im`, civicrm_worldregion.id as worldregion_id, civicrm_worldregion.name as `world_region`',
-            2 => 'WHERE 1 AND displayRelType.relationship_type_id = 1
+            2 => 'WHERE displayRelType.relationship_type_id = 1
 AND   displayRelType.is_active = 1
 AND ( 1 ) AND (contact_a.is_deleted = 0)',
           ],