想象一下拍卖(例如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
{/ 1}} 或auctions.auction_startPrice
{/ 1>},具体取决于取决于哪个这是更高的,如第一段所述。
这可以理解吗?我知道如何使用2个查询来完成此操作,但我希望可以通过1个查询来完成。
谢谢!
编辑:只是进一步的解释,以帮助您想象问题。如果我设置了bid_price
,那么我将获得5次初始竞价价格最低的竞价,但是如果这些竞价已经出价呢?然后他们当前的最低价格等于那些出价,而不是起始价格,因此我的查询是错误的。
答案 0 :(得分:2)
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;
注意:
MAX(bid_price)
列与startprice
进行比较,并且仅当最高出价不为空(比较时隐式要求)且大于起始价格时,则最高出价变为higherPrice
列中的值。否则,它将包含起始价格。higherPrice
答案 1 :(得分:0)
我不确定您正在使用哪个数据库,但请查看此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