在JOIN中获得最高结果

时间:2010-06-18 08:50:02

标签: sql mysql join

我有三张桌子;拍卖,拍卖出价和用户。表结构如下所示:

Auctions:

 id    title
 --    -----
  1     Auction 1
  2     Auction 2

Auction Bids:

 id    user_id    auction_id    bid_amt
 --    -------    ----------    -------
  1       1            1          200.00
  2       2            1          202.00
  3       1            2          100.00

Users只是一个标准表,包含id和用户名。

我的目标是加入这些表格,以便获得这些出价的最高价值,并获取与这些出价相关的用户名;所以我有一个像这样的结果集:

auction_id    auction_title    auctionbid_amt    user_username
----------    -------------    --------------    -------------
         1    Auction 1            202.00            Bidder2
         2    Auction 2            100.00            Bidder1

到目前为止,我的查询如下:

SELECT a.id, a.title, ab.bid_amt, u.display_name FROM auction a
    LEFT JOIN auctionbid ab ON a.id = ab.auction_id
        LEFT JOIN users u ON u.id = ab.user_id
GROUP BY a.id

这会获得我追求的单行,但它似乎显示最低的bid_amt,而不是最高的。

5 个答案:

答案 0 :(得分:8)

您可以使用MAX功能和子选择来获得每次拍卖的最高出价。如果您将此子选择与其他表连接并按如下所示设置where子句,则应该得到您要查找的内容。

SELECT a.id, a.title, ab.bid_points, u.display_name 
FROM Auction AS a
INNER JOIN (SELECT auction_id, MAX(bid_points) AS maxAmount FROM auction_bids GROUP BY auction_id) AS maxBids ON maxBids.auction_id = a.id
INNER JOIN auction_bids AS ab ON a.id = ab.auction_id
INNER JOIN users AS u ON u.id = ab.user_id
WHERE ab.auction_id = maxBids.auction_id AND ab.bid_amount = maxBids.maxAmount

希望有所帮助。

答案 1 :(得分:1)

这是一个典型的组内聚合问题。您可以使用所谓的左自我排除连接

来解决它

尝试以下方法:

SELECT a.id, a.title, ab.bid_points, u.displayname
  FROM auction a
  INNER JOIN auction_bids ab ON ab.auction_id = a.id
  LEFT JOIN auction_bids b1 ON ab.auction_id = b1.auction_id
    AND ab.bid_points < b1.bid_points
  LEFT JOIN users u ON u.id = ab.user_id
  WHERE b1.auction_id IS NULL

它基本上在左侧和右侧之间建立连接,直到它再也找不到左侧的连接,那就是最高的元素。

另一种解决方案是使用多个查询(当然)或临时聚合表。

答案 2 :(得分:0)

试试这个:

SELECT a.id, a.title, ab.bid_points, u.display_name FROM auction a
    LEFT JOIN auctionbid ab ON a.id = ab.auction_id
        LEFT JOIN users u ON u.id = ab.user_id
GROUP BY a.id
ORDER BY ab.bid_points DESC

如果这不起作用,请尝试在包含

之类的拍卖品上使用子选择
SELECT id, user_id, auction_id, MAX(bid_amt) FROM action_bids GROUP BY auction_id

答案 3 :(得分:0)

尝试添加以下子句;不确定性能。

WHERE NOT EXISTS
   (SELECT * FROM auctionbid abhigher
    WHERE abhigher.auction_id = ab.auction_id
    AND   abhigher.auctionbid_amt > ab.auctionbid_amt)

从同一拍卖的出价较高的查询中排除竞价出价。

唯一的问题是,如果您有2个相同的出价并且两者都会列出。摆脱它们的一种方法 - 但它是一个相对随意的赢家选择,是使用出价ID:

WHERE NOT EXISTS
   (SELECT * FROM auctionbid abhigher
    WHERE abhigher.auction_id = ab.auction_id
    AND   abhigher.auctionbid_amt >= ab.auctionbid_amt
    AND   abhigher.id > ab.id)

答案 4 :(得分:0)

这是你可以尝试的东西..就像旧学校......没什么新的......不需要去左联或其他任何东西......很大程度上取决于你的确切要求

select A.id,A.title,max(AB.bid_amt),name
from Auction A,AuctionBids AB,Users U
where U.ID=AB.USER_ID AND A.ID=AB.ID
group by A.ID,A.title,name