表别名不能与join一起使用

时间:2016-01-08 14:58:46

标签: mysql

我在此查询中收到错误Unknown column 'sch1.laestab' in 'field list'

SELECT
    sch1.laestab AS eef_sch_id,
    sch1.sch_name AS sch_name,
    sch1.urn AS sch_dfe,
    foo1.*
FROM tbl_Schools as sch1
JOIN (
    SELECT
    sch2.laestab AS eef_sch2_id,
    sch2.sch_name AS sch2_name,
    sch2.urn AS sch2_dfe
    FROM tbl_SimilarSchools ss2
    JOIN tbl_Schools sch2 ON sch2.laestab = ss2.cluster_id
    WHERE cluster_id = sch1.laestab
    AND cluster_id != school_id
    AND sch2.use_KS4 = '1'
    ORDER BY distance2 ASC
    LIMIT 1
) as foo1

但如果删除JOIN部分,则可以正常工作。我的结构有什么问题?

1 个答案:

答案 0 :(得分:0)

你在JOIN里面有一个拼写错误:

WHERE cluster_id = sch1.laestab

应该是

WHERE cluster_id = sch2.laestab

或者,如果这不是拼写错误,那么您应该将此检查移出加入' ON'部分。像这样的东西

JOIN (
    SELECT
    cluster_id,
    sch2.laestab AS eef_sch2_id,
    sch2.sch_name AS sch2_name,
    sch2.urn AS sch2_dfe
    FROM tbl_SimilarSchools ss2
    JOIN tbl_Schools sch2 ON sch2.laestab = ss2.cluster_id
    WHERE cluster_id != school_id
    AND sch2.use_KS4 = '1'
    ORDER BY distance2 ASC
    LIMIT 1
) as foo1
on foo1.cluster_id = sch1.laestab