mysql in 关联子查询,MySQL关联子查询

Can any one help me i have problem with Correlated nested sub queries

i.e., when i am trying to use grand parent column in nested sub query then i got this error

Error Code: 1054

Unknown column 'scu.iUserId' in 'where clause'

Query:

SELECT

scu.iUserId,

(SELECT

SUM(

sbs.`iNoPointsBeginning` +

(SELECT

COALESCE(SUM(BehaviorPts), 0) AS StudentPts

FROM

(SELECT

(

COUNT(sbis.iIncidentSubmissionId) * sbi.iPointValue

) AS BehaviorPts

FROM

scn_behavior_incident_submission sbis

JOIN scn_behavior_incident_actors sbia

ON sbia.iIncidentSubmissionId = sbis.iIncidentSubmissionId

LEFT JOIN scn_behavior_incidents sbi

ON sbi.iIncidentId = sbis.iBehaviorIncidentId

WHERE sbia.iUserId = scu.iUserId

AND sbia.eActorType 'Witness'

AND sbis.iSchoolId = '875'

GROUP BY sbis.iBehaviorIncidentId) AS BehaviorTotal)

) AS stu_pt

FROM

scn_behavior_settings sbs

WHERE sbs.`iSchoolId` = '875')

FROM

scn_sections_members AS scm

INNER JOIN scn_users AS scu

ON scu.iUserId = scm.iStudentId

解决方案

The two levels of nesting cause this error. The very internal subquery does not "know" scu which is defined in the external query.

Try to rewrite it without inline subqueries. Not sure if this is the proper way but you'll get the idea. (the sbs table seems unrelated to the other ones so I made that a CROSS JOIN. Edit appropriately if there is a relationship):

SELECT

scu.iUserId,

sbs.iNoPointsBeginning

+ COUNT(sbis.iIncidentSubmissionId) * COALESCE(sbi.iPointValue, 0)

AS stu_pt

FROM

( SELECT

SUM(sbs.iNoPointsBeginning) AS iNoPointsBeginning

FROM

scn_behavior_settings sbs

WHERE sbs.iSchoolId = '97'

) AS sbs

CROSS JOIN

scn_sections_members AS scm

INNER JOIN scn_users AS scu

ON scu.iUserId = scm.iStudentId

LEFT JOIN

scn_behavior_incident_submission sbis

JOIN scn_behavior_incident_actors sbia

ON sbia.iIncidentSubmissionId = sbis.iIncidentSubmissionId

AND sbia.eActorType = 'Witness'

AND sbis.iSchoolId = '97'

LEFT JOIN scn_behavior_incidents sbi

ON sbi.iIncidentId = sbis.iBehaviorIncidentId

ON sbia.iUserId = scu.iUserId

GROUP BY scu.iUserId

, sbis.iBehaviorIncidentId

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值