sql - 在 JOIN 中获得最高结果

标签 sql mysql join

我有三张 table ;拍卖、拍卖出价和用户。表结构看起来像这样:

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,而不是最高的。

最佳答案

您可以使用 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

希望对您有所帮助。

关于sql - 在 JOIN 中获得最高结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3068268/

相关文章:

php - Uncaught Error : Undefined class constant 'ERRMODE_EXPECTION'

php - 从 mysql 检索数据

mysql - SQL 这是外连接还是内连接以及如何在数组上连接

php - 加入 2 个表并从另一个表中获取不同的最新条目

sql - 如何查看 X++ select 语句的 SQL 表达式?

php - 根据分隔符拆分列值?

mysql - 如何从 "exists"查询(MYSQL)中取出值?

mysql - 连接到第二个表,其中某个字段的字符出现次数最多

php - 输入类型的文件不起作用:ajax到php

php - mysql select/delete using join over 四个表