The multi-part identifier could not be bound - SubQuery

后端 未结 2 1602
被撕碎了的回忆
被撕碎了的回忆 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 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
    

提交回复
热议问题