The multi-part identifier could not be bound - SubQuery

后端 未结 2 1601
被撕碎了的回忆
被撕碎了的回忆 2021-01-04 03:10

Schema:

create table TableA (A1 int)
create table TableB (B1 int, B2 int)
create table TableC (C1 int)

Problematic query:

S         


        
相关标签:
2条回答
  • 2021-01-04 03:59

    You cannot access an alias from a join inside of another joined subquery. You will need to use the following which joins the subquery on two columns/tables:

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

    Or this can be written as:

    SELECT * 
    FROM TableA a
    INNER JOIN TableB b 
      ON b.B1=a.A1
    INNER JOIN TableC c
      ON c.C2=b.B2
      AND c.C1 = b.B1
    
    0 讨论(0)
  • 2021-01-04 04:02

    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
    
    0 讨论(0)
提交回复
热议问题