Mysql

使用 MAX 連接 3 個表

  • November 22, 2018

概述

我正在嘗試加入 3 個表auctionbidsusers。我需要基於表格的每個表格中的幾個關鍵資訊bids。最後,我想對拍賣進行簡要概述。查看每次拍賣的最新出價和放置它的使用者。

我習慣於執行簡單的 SQL 查詢,但我不確定我需要做什麼才能完成此操作。不是在尋找解決方案(儘管我會接受解釋),而是在學習經驗。

表結構

拍賣

id, title,location

出價

id, auction_id, user_id,bid_amount

使用者

id, name,address

查詢至今

到目前為止,這是我開始的,非常感謝任何關於從這裡做什麼的指導。

SELECT 
   MAX(bids.id) AS 'Bid ID',
   bids.auction_id AS 'Auction ID',
   auctions.title AS 'Auction Title',
   MAX(bids.bid_amount) AS 'Bid Amount'
FROM
   boardman_bidding.bids
       INNER JOIN
   boardman_bidding.auctions ON bids.auction_id = auctions.id
       INNER JOIN
   boardman_bidding.users ON bids.user_id = users.id
WHERE
   bids.auction_id > 1065 AND
   auctions.city_id = '45621'
GROUP BY bids.auction_id
ORDER BY bids.auction_id DESC;

預期產出

我希望有以下幾點:

bid_id, auction.title, auction.location, users.user_id, users.name, users.location,bid_amount

假設:bid.id 總是遞增的。你說你想要最新的出價。從技術上講,“最新”是由時間定義的,而不是由 ID 定義的——但我沒有在您的投標表中看到任何時間列,所以我假設 ID 號是增量發布的(總是增加)。在這種情況下,max(ID) 將是最新的。

以下應該工作。理論上,您可以將子查詢移動到連接中,但需要計算連接條件中的最新投標 ID,這很難閱讀。實際上,最後三個子查詢都具有相同的WHERE子句,因此優化器應該知道無論如何只查找表一次,並獲得所需的 3 個值。(除非您正在進行數百萬次拍賣,否則我認為性能不會有任何問題)。

select
   auctions.title as Auction_Title,
   auctions.location as Auction_Location,
   (select max(bids.id) from bids where bids.auction_id = auctions.id) as Latest_Bid_ID,
   (select amount from bids where id = Latest_Bid_ID) as Bid_Amount,
   (select users.id from users join bids on bids.user_id = users.id where bids.id = Latest_Bid_ID) as User_ID,
   (select users.name from users join bids on bids.user_id = users.id where bids.id = Latest_Bid_ID) as User_Name,
   (select users.location from users join bids on bids.user_id = users.id where bids.id = Latest_Bid_ID) as User_Location
from
   auctions
order by auctions.title
;

引用自:https://dba.stackexchange.com/questions/223160