@@ -1589,25 +1589,24 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
1589
1589
for (i = 0 ; i < p -> pSrc -> nSrc ; i ++ ){
1590
1590
SrcItem * pItem = & p -> pSrc -> a [i ];
1591
1591
if ( pItem -> pSelect && (pItem -> pSelect -> selFlags & SF_Resolved )== 0 ){
1592
- NameContext * pNC ; /* Used to iterate name contexts */
1593
- int nRef = 0 ; /* Refcount for pOuterNC and outer contexts */
1592
+ int nRef = pOuterNC ? pOuterNC -> nRef : 0 ;
1594
1593
const char * zSavedContext = pParse -> zAuthContext ;
1595
1594
1596
- /* Count the total number of references to pOuterNC and all of its
1597
- ** parent contexts. After resolving references to expressions in
1598
- ** pItem->pSelect, check if this value has changed. If so, then
1599
- ** SELECT statement pItem->pSelect must be correlated. Set the
1600
- ** pItem->fg.isCorrelated flag if this is the case. */
1601
- for (pNC = pOuterNC ; pNC ; pNC = pNC -> pNext ) nRef += pNC -> nRef ;
1602
-
1603
1595
if ( pItem -> zName ) pParse -> zAuthContext = pItem -> zName ;
1604
1596
sqlite3ResolveSelectNames (pParse , pItem -> pSelect , pOuterNC );
1605
1597
pParse -> zAuthContext = zSavedContext ;
1606
1598
if ( pParse -> nErr || db -> mallocFailed ) return WRC_Abort ;
1607
1599
1608
- for (pNC = pOuterNC ; pNC ; pNC = pNC -> pNext ) nRef -= pNC -> nRef ;
1609
- assert ( pItem -> fg .isCorrelated == 0 && nRef <=0 );
1610
- pItem -> fg .isCorrelated = (nRef != 0 );
1600
+ /* If the number of references to the outer context changed when
1601
+ ** expressions in the sub-select were resolved, the sub-select
1602
+ ** is correlated. It is not required to check the refcount on any
1603
+ ** but the innermost outer context object, as lookupName() increments
1604
+ ** the refcount on all contexts between the current one and the
1605
+ ** context containing the column when it resolves a name. */
1606
+ if ( pOuterNC ){
1607
+ assert ( pItem -> fg .isCorrelated == 0 && pOuterNC -> nRef >=nRef );
1608
+ pItem -> fg .isCorrelated = (pOuterNC -> nRef > nRef );
1609
+ }
1611
1610
}
1612
1611
}
1613
1612
0 commit comments