'assemble a WHERE clause which retrieves a given state by primary
key, using a minimized set of tables.
Applies to a joined-table inheritance mapper where the
requested attribute names are only present on joined tables,
not the base table.  The WHERE clause attempts to include
only those tables to minimize joins.'

def _optimized_get_statement(self, state, attribute_names):

    props = self._props
    tables = set(chain(*[sql_util.find_tables(c, check_columns=True) for key in attribute_names for c in props[key].columns]))
    if (self.base_mapper.local_table in tables):
        return None
    class ColumnsNotAvailable(Exception, ):
        pass
    def visit_binary(binary):
        leftcol = binary.left
        rightcol = binary.right
        if ((leftcol is None) or (rightcol is None)):
            return
        if (leftcol.table not in tables):
            leftval = self._get_committed_state_attr_by_column(state, state.dict, leftcol, passive=attributes.PASSIVE_NO_INITIALIZE)
            if ((leftval is attributes.PASSIVE_NO_RESULT) or (leftval is None)):
                raise ColumnsNotAvailable()
            binary.left = sql.bindparam(None, leftval, type_=binary.right.type)
        elif (rightcol.table not in tables):
            rightval = self._get_committed_state_attr_by_column(state, state.dict, rightcol, passive=attributes.PASSIVE_NO_INITIALIZE)
            if ((rightval is attributes.PASSIVE_NO_RESULT) or (rightval is None)):
                raise ColumnsNotAvailable()
            binary.right = sql.bindparam(None, rightval, type_=binary.right.type)
    allconds = []
    try:
        start = False
        for mapper in reversed(list(self.iterate_to_root())):
            if (mapper.local_table in tables):
                start = True
            elif (not isinstance(mapper.local_table, expression.TableClause)):
                return None
            if (start and (not mapper.single)):
                allconds.append(visitors.cloned_traverse(mapper.inherit_condition, {}, {'binary': visit_binary}))
    except ColumnsNotAvailable:
        return None
    cond = sql.and_(*allconds)
    cols = []
    for key in attribute_names:
        cols.extend(props[key].columns)
    return sql.select(cols, cond, use_labels=True)
