private static int stageIndexOf(
        final List<StageBean<?>> stages,
        final HasComparableOperators<?, ?> foreignField,
        final int index
    ) {
        // First check if there is exactly one that is matching
        final Set<Integer> matches = new LinkedHashSet<>();
        final String foreignTableIdentifierString = tableIdentifierString(foreignField);

        for (int i = 0; i < stages.size(); i++) {
            final StageBean<?> stage = stages.get(i);
            final String fieldTableIdentifierString = tableIdentifierString(stage);
            if (fieldTableIdentifierString.equals(foreignTableIdentifierString)) {
                matches.add(i);
            }
        }
        if (matches.size() > 1) {
            throw new IllegalStateException(
                "The identifier " + foreignTableIdentifierString + " for stage index " + index + " is ambiguous. "
                    + "There are matching table identifiers for stage indexes " + matches
                    + ". These table identifiers are available from previous join stages: "
                    + stages.stream().map(AbstractJoinBuilder::tableIdentifierString).collect(joining(", "))
            );
        } else if (matches.size() == 1) {
            return matches.iterator().next();
        }
        throw new IllegalStateException(
            "There is no table for table identifier \"" + tableIdentifierString(foreignField) + "\" for stage index " + index + " of [0, " + (stages.size() - 1) + "]"
                + ". These table identifiers are available from previous join stages: "
                + stages.stream().map(AbstractJoinBuilder::tableIdentifierString).collect(joining(", "))
        );

    }
Calculates which reference to use taking "as()" columns into account.
runtime-parent/runtime-join/src/main/java/com/speedment/runtime/join/internal/component/join/AbstractJoinBuilder.java