架构:
create table TableA (A1 int) create table TableB (B1 int, B2 int) create table TableC (C1 int)
问题查询:
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
生成此架构并在SQL Server 2008下在SQLFiddle中运行查询将导致:
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
对子查询使用CROSS APPLY而不是INNER JOIN可以解决此问题
有什么问题?
编辑:我添加了“ TOP 1”,它是真正查询的一部分,并且是问题的相关部分。
Edit2:有关该问题的更多信息。
您不能将fromJOIN子句引用到JOIN的另一部分。
JOIN
改用它。
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
已编辑
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)
要TableC在JOIN-s中进一步使用,可以使用它。
TableC
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