在JOIN中使用带有“AS”的字段的指定名称

时间:2014-08-29 15:42:07

标签: mysql sql join left-join coalesce

我有这段代码..

SELECT u.*, COALESCE(c2.name,u.state) AS real_state, c.name AS real_country, bc.alpha3 AS country_iso FROM gimko_v2.users AS u
        INNER JOIN gimko_v2.countries AS c ON u.country=c.id 
        LEFT JOIN gimko_v2.countries AS c2 ON u.state=c2.id 
        LEFT JOIN gimko_blesta.countries AS bc ON c.country_iso_code=bc.alpha2
        LEFT JOIN gimko_blesta.states AS bs ON bc.alpha2=bs.country_alpha2 AND real_state=bs.name
        WHERE u.blesta_id=0;

这方面的问题很喜欢:

COALESCE(c2.name,u.state) AS real_state

LEFT JOIN gimko_blesta.states AS bs ON bc.alpha2=bs.country_alpha2 AND real_state=bs.name

我收到此错误:

Error Code: 1054
Unknown column 'real_state' in 'on clause'

如何在COALESCE(c2.name,u.state)中使用JOIN的结果?

谢谢!

2 个答案:

答案 0 :(得分:2)

您不能在查询的同一级别使用虚拟别名,您可能需要重复整个表达式或使用子选择来访问父查询

SELECT * FROM (
SELECT u.*, 
COALESCE(c2.name,u.state) AS real_state,
c.name AS real_country,
bc.alpha3 AS country_iso ,
bc.alpha2
FROM gimko_v2.users AS u
        INNER JOIN gimko_v2.countries AS c ON u.country=c.id 
        LEFT JOIN gimko_v2.countries AS c2 ON u.state=c2.id 
        LEFT JOIN gimko_blesta.countries AS bc ON c.country_iso_code=bc.alpha2
) t
LEFT JOIN gimko_blesta.states AS bs ON t.alpha2=bs.country_alpha2 AND t.real_state=bs.name
WHERE t.blesta_id=0;

同样在子选择中,您必须选择将在外部联接中用于父查询的所有必需列,例如在我的情况下我在内部查询中选择了bc.alpha2,因为要加入states这个专栏是必需的

答案 1 :(得分:2)

gimko_blesta.states是否需要在源表中?它的所有列都不在选择列表/条件中,并且它与LEFT JOIN一起加入,因此看起来似乎不是必需的。

在任何情况下,您都需要首先将它作为派生表,并将gimko_blesta.states连接到派生表,或者只使用JOIN中的表达式,如下面的COALESCE(c2.name,u.state) = bs.name

SELECT u.*, COALESCE(c2.name,u.state) AS real_state, c.name AS real_country, bc.alpha3 AS country_iso 
FROM gimko_v2.users AS u
        INNER JOIN gimko_v2.countries AS c ON u.country=c.id 
        LEFT JOIN gimko_v2.countries AS c2 ON u.state=c2.id 
        LEFT JOIN gimko_blesta.countries AS bc ON c.country_iso_code=bc.alpha2
        LEFT JOIN gimko_blesta.states AS bs ON bc.alpha2=bs.country_alpha2 AND COALESCE(c2.name,u.state) = bs.name
        WHERE u.blesta_id=0;