The multi-part identifier could not be bound - SubQuery

inner-join, join, sql, sql-server-2008, subquery

Solution

you can't reference from `JOIN` clause to another part of JOIN.

Use this instead.

SELECT * 
FROM TableA a
INNER JOIN TableB b
    ON b.B1=a.A1
INNER JOIN TableC c
    ON d.C2=b.B2
      AND c.C1=b.B1

EDITED

SELECT * 
FROM TableA a
INNER JOIN TableB b ON b.B1=a.A1
WHERE b.B2 = (SELECT TOP 1 c.C2 
               FROM TableC c
               WHERE c.C1=b.B1 ORDER BY c.C1)

For further use of `TableC` in JOIN-s you can use this.

SELECT * 
FROM TableA a
    INNER JOIN TableB b
        ON b.B1=a.A1
    INNER JOIN
       (
           SELECT
               ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY C2) RN,
               C2
               --, other columns fromTableC if needed
           FROM TableC
       ) CC
     ON b.B2 = CC.C2
       AND CC.RN = 1

Problem

Schema: ``` create table TableA (A1 int) create table TableB (B1 int, B2 int) create table TableC (C1 int) ``` Problematic query: ``` SELECT * FROM TableA a INNER JOIN TableB b ON b.B1=a.A1 INNER JOIN (SELECT TOP 1 * FROM TableC c WHERE c.C1=b.B1 ORDER BY c.C1) d ON d.C2=b.B2 INNER JOIN OtherTable ON OtherTable.Foo=d.C1 ``` Building this schema and running the query in SQLFiddle under SQL Server 2008 results in: ``` The multi-part identifier "b.B1" could not be bound.: SELECT * FROM TableA a INNER JOIN TableB b ON b.B1=a.A1 INNER JOIN (SELECT TOP 1 * FROM TableC c WHERE c.C1=b.B1 ORDER BY c.C1) d ON d.C2=b.B2 ``` Using CROSS APPLY instead of INNER JOIN for the subquery fixes the issue What's the problem? Edit: I added "TOP 1" that was part of the real query and it's a relevant part of the problem. Edit2: Further information about the problem.

Original source