'A helper method for get_distinct and get_ordering. This method will
trim extra not-needed joins from the tail of the join chain.
This is very similar to what is done in trim_joins, but we will
trim LEFT JOINS here. It would be a good idea to consolidate this
method and query.trim_joins().'

def _final_join_removal(self, cols, alias):

    if alias:
        while 1:
            join = self.query.alias_map[alias]
            (lhs_cols, rhs_cols) = zip(*[(lhs_col, rhs_col) for (lhs_col, rhs_col) in join.join_cols])
            if (set(cols) != set(rhs_cols)):
                break
            cols = [lhs_cols[rhs_cols.index(col)] for col in cols]
            self.query.unref_alias(alias)
            alias = join.lhs_alias
    return (cols, alias)
