开发者

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

Imagine an auction (ebay auction, for example). You create an auction, set the start bidding value, let's say, 5 dollars. This gets stored as a minimal bid value to the auctions table.At this point, the current bid value of this auction is 5 dollars.

Now, if someone bids to your auction, let's say, 10 dollars, this gets stored to the bids table.At this point, the current bid value of this auction is 10 dollars.

Now let's imagine you want to retrieve 5 cheapest auctions. You will write a query like this:

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

Pretty simple, and it works! B开发者_高级运维ut now you need to add an ORDER BY clause to the query. The problem is, however, that we want to ORDER BY either by auctions.auction_startPrice or by bid_price, depending on whichever of this is higher, as explained in the first paragraphs.

Can this be understood? I know how to do this using 2 queries, but I am hoping it can be done with 1 query.

Thanks!

EDIT: Just a further explanation to help you imagine the problem. If I set ORDER BY auction_startPrice ASC, then I will get 5 auctions with their lowest initial bid price, but what if there are already bids placed on those auctions? Then their current lowest price is equal to those bids, NOT to the start price, therefore my query is wrong.


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;

Note:

  1. In the inner query, an extra column is created, named 'higherPrice'
  2. The IF function compares the MAX(bid_price) column against the startprice, and only if the Max-bid is not null (implicitly required in comparison) and greater than start price, then the Max-bid becomes the value in the higherPrice column. Otherwise, it will contain the start price.
  3. The outer query merely makes use of the columns from the inner query, ordering by the higherPrice


I'm not sure which database you're using but look at this example: 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜