diff --git a/src/backend/catalog/namespace.c b/src/backend/catalog/namespace.c
index 65e271a..6c4c76a 100644
--- a/src/backend/catalog/namespace.c
+++ b/src/backend/catalog/namespace.c
@@ -4050,6 +4050,22 @@ ResetTempTableNamespace(void)
 		RemoveTempRelations(myTempNamespace);
 }
 
+/*
+ * Remove all temp tables from the temporary namespace for the specified backend id.
+ */
+void
+ResetTempTableNamespaceForBackendId(BackendId backendId)
+{
+	char		namespaceName[NAMEDATALEN];
+	Oid			namespaceId;
+
+	snprintf(namespaceName, sizeof(namespaceName), "pg_temp_%d", backendId);
+
+	namespaceId = get_namespace_oid(namespaceName, true);
+	if (OidIsValid(namespaceId))
+		RemoveTempRelations(namespaceId);
+}
+
 
 /*
  * Routines for handling the GUC variable 'search_path'.
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index 702f8d8..60fb1c5 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -2071,13 +2071,15 @@ do_autovacuum(void)
 		if (classForm->relpersistence == RELPERSISTENCE_TEMP)
 		{
 			int			backendID;
+			PGPROC		*proc;
 
 			backendID = GetTempNamespaceBackendId(classForm->relnamespace);
 
-			/* We just ignore it if the owning backend is still active */
+			/* We just ignore it if the owning backend is still active and connected to this database */
 			if (backendID != InvalidBackendId &&
 				(backendID == MyBackendId ||
-				 BackendIdGetProc(backendID) == NULL))
+				 (proc = BackendIdGetProc(backendID)) == NULL ||
+				 proc->databaseId != MyDatabaseId))
 			{
 				/*
 				 * The table seems to be orphaned -- although it might be that
diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c
index 4846289..9549b43 100644
--- a/src/backend/utils/init/postinit.c
+++ b/src/backend/utils/init/postinit.c
@@ -1031,6 +1031,10 @@ InitPostgres(const char *in_dbname, Oid dboid, const char *username,
 	/* set default namespace search path */
 	InitializeSearchPath();
 
+	/* remove all temporary tables from the temporary namespace */
+	if (!bootstrap && !RecoveryInProgress())
+		ResetTempTableNamespaceForBackendId(MyBackendId);
+
 	/* initialize client encoding */
 	InitializeClientEncoding();
 
diff --git a/src/include/catalog/namespace.h b/src/include/catalog/namespace.h
index 5f8cf49..e7cb205 100644
--- a/src/include/catalog/namespace.h
+++ b/src/include/catalog/namespace.h
@@ -133,6 +133,7 @@ extern void GetTempNamespaceState(Oid *tempNamespaceId,
 extern void SetTempNamespaceState(Oid tempNamespaceId,
 					  Oid tempToastNamespaceId);
 extern void ResetTempTableNamespace(void);
+extern void ResetTempTableNamespaceForBackendId(BackendId backendId);
 
 extern OverrideSearchPath *GetOverrideSearchPath(MemoryContext context);
 extern OverrideSearchPath *CopyOverrideSearchPath(OverrideSearchPath *path);
