MySQL JOIN语法,看不到错误原因

时间:2019-01-22 20:53:08

标签: mysql

我正在努力寻找此查询失败的原因

SELECT
fID, Date, host_id, t1.tname AS opposition, HA, opp_id, t2.club_id AS clubid, c.club, c.venue
FROM(
SELECT
id fID,
hteam_id host_id,
date Date,
CASE WHEN (hteam_id='13') THEN 'H' ELSE 'NULL' END HA,
ateam_id opp_id
FROM fixtures WHERE hteam_id='13'
UNION ALL
SELECT
id,
hteam_id,
date,
CASE WHEN (ateam_id='13') THEN 'A' ELSE 'NULL' END,
hteam_id
FROM fixtures WHERE ateam_id='13'
) as tot
JOIN teams t1 ON tot.opp_id=t1.id
JOIN teams t2 ON tot.host_id=t2.id
JOIN clubs c ON tot.clubid=c.id
ORDER BY Date ASC

一切都很好,直到我在桌球俱乐部上添加了第三个JOIN。

错误#1054-“ on子句”中的未知列“ tot.clubid”

1 个答案:

答案 0 :(得分:1)

如果正确设置代码格式,您将更容易看到。表clubid上没有列tot

SELECT fID
    , Date
    , host_id
    , t1.tname AS opposition
    , HA, opp_id
    , t2.club_id AS clubid
    , c.club, c.venue
FROM(
    SELECT
        id fID,
        hteam_id host_id,
        date Date,
        CASE WHEN (hteam_id='13') THEN 'H' ELSE 'NULL' END HA,
        ateam_id opp_id
    FROM fixtures 
    WHERE hteam_id='13'
    UNION ALL
    SELECT
        id,
        hteam_id,
        date,
        CASE WHEN (ateam_id='13') THEN 'A' ELSE 'NULL' END,
        hteam_id
    FROM fixtures 
    WHERE ateam_id='13'
) as tot
JOIN teams t1 ON tot.opp_id=t1.id
JOIN teams t2 ON tot.host_id=t2.id
JOIN clubs c ON tot.clubid=c.id
ORDER BY Date ASC