子查询 table - 别名在 JOIN-ON/WHERE 中未被识别

Subquery table-alias not being recognized in JOIN-ON/WHERE

我正在尝试向业余爱好者朋友提供一些帮助,使用 SQL 服务器经验来帮助 MySQL。

他正在研究游戏数据库。我为他写了这个查询

SELECT ib.itemid, ii.realname as name, ib.stackSize,
       IFNULL(ah.price, '-') as price, ah.stock
    FROM item_basic ib
    LEFT OUTER JOIN item_info as ii ON ii.itemID = ib.itemID
    LEFT OUTER JOIN (SELECT price, COUNT(*) as stock
        FROM auction_house
        GROUP BY itemID) as AH on ii.itemID = AH.itemID -- erring line
    ORDER BY ii.realname

还有一个版本使用 FROM 子句而不是 JOIN 组装子查询,但比这个版本麻烦少。

这给出了错误 Unknown column 'ah.itemID' in 'on clause'

如果我错误地将错误行更改为 ... ii.itemID = ib.itemID,查询会执行,但结果当然是不正确的(在这种情况下呈指数倍增)。

这是一个带有示例数据的 SQL Fiddle

没有AH.itemID,只能访问子查询的结果。

这是因为您没有在子查询中选择 itemID。此外,您选择了价格列而不按它进行聚合。尝试替换

LEFT OUTER JOIN (SELECT price, COUNT(*) as stock
        FROM auction_house
        GROUP BY itemID) as AH on ii.itemID = AH.itemID

LEFT OUTER JOIN (SELECT itemID, price, COUNT(*) as stock
        FROM auction_house
        GROUP BY itemID, price) as AH on ii.itemID = AH.itemID