如何将一个表中的一行连接到具有另一表上给定列的MAX值的行?
例如,我有一张auctions桌子和一张auction_bids桌子。我想以表中该拍卖的最高出价(即列bid_amountAND的最高值,其中auction_id= x)加入拍卖auction_bids表。
auctions
auction_bids
bid_amount
auction_id
x
这很烦人。您最好在每个获胜的Auction_bid中都带有一个“优胜者”标志。
SELECT * FROM auctions a INNER JOIN ( /* now get just the winning rows */ SELECT * FROM auction_bids x INNER JOIN ( /* how to tell the winners */ SELECT auction_id, MAX(bid_amount) as winner FROM auction_bids GROUP BY auction_id ) y ON x.auction_id = y.auction_id AND x.bid_amount = y.winner ) b ON a.auction_id = b.auction_id
请注意,竞标价为零的竞标价将根本不会列出,而有关联的竞标(会发生这种情况)将为每个并列竞标出现一次。