简体   繁体   中英

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

I'm trying to lend some help to a hobbyist friend, using SQL Server experience to help with MySQL.

He's working on a game database. I wrote this query for him

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

And a version that used assembled the subquery in the FROM cluse rather than a JOIN, but that was less troublesome than this version.

This gives the error Unknown column 'ah.itemID' in 'on clause'

If I change the erring line, incorrectly, to ... ii.itemID = ib.itemID , the query executes, but of course the results are incorrect (exponentially doubled in this case).

Here's an SQL Fiddle with sample data.

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

It's because you're not selecting itemID in your subquery. In addition, you're selecting the price column without aggregating by it. Try replacing

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

with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM