簡體   English   中英

如何在SQL查詢中將ORDER BY設置為依賴於SQL查詢本身的值?

[英]How do I set ORDER BY in SQL query to a value depending by the SQL query itself?

想象一下拍賣(例如ebay拍賣)。 您創建一個拍賣,設置起始出價值,比方說,5美元。 這將作為最小出價值存儲到auctions表中。此時,此拍賣的當前出價值為5美元

現在,如果某人競標您的拍賣,比方說,10美元,則會將其存儲到bids表中。此時,此次競價的當前出價為10美元

現在讓我們假設您要檢索5個最便宜的拍賣。 您將編寫如下查詢:

SELECT
`auction_id`,
`auction_startPrice`,
MAX(bids.bid_price) as `bid_price`
FROM
`auctions`
LEFT JOIN `bids` ON `auctions`.`auction_id`=`bids`.`bid_belongs_to_auction`
GROUP BY `auction_id`
LIMIT 5

很簡單,它的工作原理! 但是現在需要在查詢中添加ORDER BY子句。 問題是,然而,我們要ORDER BY要么 auctions.auction_startPrice bid_price ,取決於兩者的這種較高 ,如在第一段落解釋。

這可以理解嗎? 我知道如何使用2個查詢來執行此操作,但我希望可以使用1個查詢完成此操作。

謝謝!

編輯:只是進一步解釋,以幫助您想象問題。 如果我設置ORDER BY auction_startPrice ASC ,那么我將獲得最低初始出價的5次拍賣,但是如果這些拍賣已經有出價呢? 然后他們當前的最低價格等於那些出價,而不是起始價格,因此我的查詢是錯誤的。

SELECT
  `auction_id`,
  `auction_startPrice`,
  `bid_price`
FROM
(
    SELECT
        `auction_id`,
        `auction_startPrice`,
        MAX(bids.bid_price) as `bid_price`,
        IF(MAX(bids.bid_price)>`auction_startPrice`,
           MAX(bids.bid_price),
           `auction_startPrice`) higherPrice
    FROM
    `auctions`
    LEFT JOIN `bids` ON `auctions`.`auction_id`=`bids`.`bid_belongs_to_auction`
    GROUP BY `auction_id`
) X
order by higherPrice desc
LIMIT 5;

注意:

  1. 在內部查詢中,創建了一個額外的列,名為“higherPrice”
  2. IF函數將MAX(bid_price)列與startprice進行比較,並且僅當Max-bid不為空(比較中隱式需要)且大於開始價格時,Max-bid higherPrice成為higherPrice列中的值。 否則,它將包含起始價格。
  3. 外部查詢僅使用內部查詢中的列,由higherPrice排序

我不確定你使用的是哪個數據庫,但請看這個例子http//www.extremeexperts.com/sql/articles/CASEinORDER.aspx

SELECT
`auction_id`,
`auction_startPrice`,
MAX(bids.bid_price) as `bid_price`
FROM
`auctions`
LEFT JOIN `bids` ON `auctions`.`auction_id`=`bids`.`bid_belongs_to_auction`
GROUP BY `auction_id`
ORDER BY CASE WHEN `auction_startPrice` > isnull(MAX(bids.bid_price),0) then `auction_startPrice` else MAX(bids.bid_price) end
LIMIT 5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM