Mysql 检索拍卖中每个项目的前2个出价
我无法合并多个表中的数据。我尝试过联接和子查询,但没有效果。我基本上需要将两个查询合并为一个查询。我的表格简化了: 股票:Mysql 检索拍卖中每个项目的前2个出价,mysql,join,subquery,Mysql,Join,Subquery,我无法合并多个表中的数据。我尝试过联接和子查询,但没有效果。我基本上需要将两个查询合并为一个查询。我的表格简化了: 股票: id int(9) PrimaryIndex lot_number int(4) description text reserve int(9) current_bid int(9) current_bidder int(6) 成员: member_id int(11)
id int(9) PrimaryIndex
lot_number int(4)
description text
reserve int(9)
current_bid int(9)
current_bidder int(6)
成员:
member_id int(11) PrimaryIndex
name varchar(255)
投标:
我目前使用两个单独的查询,有1000个批次,这使得它非常低效。第一个问题:
SELECT S.id, S.lot_number, S.description, S.reserve FROM stock S ORDER BY
S.lot_number ASC
while循环中的第二个查询将获取投标信息:
SELECT DISTINCT B.bidder_id, B.lot_id, B.max_bid, B.time_of_bid,
M.fname, M.lname FROM bids B, members M WHERE B.lot_id=? AND
B.bidder_id=M.member_id ORDER BY B.max_bid DESC LIMIT 2
以下是我希望从单个查询中获得的输出(如果可能):
Lot No. | Reserve | Current Bid | 1st Max Bid | 1st Bidder | 2nd Max Bid | 2nd Max Bidder
1 | $100 | $120 | $150 | Steve | $110 | John
2 | $500 | $650 | $900 | Tom | $600 | Paul
我只获得了MAXB.bid及其相关细节,其中S.id=B.id,但我无法获得每个批次的前2个出价。首先将行号rn分配给表bids中每组批次id中的行,最高出价获得1,第二高出价获得2,依此类推。最高出价和第二高出价将在左联接后的两行上。使用GROUP BY将两行合并为一行
select s.lot_number, s.reserve, s.current_bid,
max( case when rn = 1 then b.max_bid end) as first_max_bid,
max( case when rn = 1 then m.name end) as first_bidder,
max( case when rn = 2 then b.max_bid end) as second_max_bid,
max( case when rn = 2 then m.name end ) as second_bidder
from
stock s
left join
(select * from
(select *,
(@rn := if(@lot_id = lot_id, @rn+1,
if( @lot_id := lot_id, 1, 1))) as rn
from bids cross join
(select @rn := 0, @lot_id := -1) param
order by lot_id, max_bid desc
) t
where rn <= 2) b
on s.lot_number = b.lot_id
left join members m
on b.bidder_id = m.member_id
group by s.lot_number, s.reserve, s.current_bid
order by s.lot_number
你能在www.sqlfiddle.com上创建一个示例数据库并在此处共享链接吗?嗨,cdaiga,我试图创建你在此处要求的内容:如果有帮助,请告诉我。如果使用sqlfiddle.com/,似乎无法获得正确的数据!9/658272,虽然示例数据库可能不完整,因为我以前没有使用过该站点,因此可能需要进行一些改进,谢谢。@HeadbangA您在sqlfiddle中的测试数据确实不完整。很多出价在stock表中没有条目。这可能有点混乱,但是stock.id等同于bids.lot\u id不是bids.id,只是我的命名不一致。它似乎与您的示例中的一些小调整一起工作。这里的工作示例:sqlfiddle.com/!9/00cb8b/1
select s.lot_number, s.reserve, s.current_bid,
max( case when rn = 1 then b.max_bid end) as first_max_bid,
max( case when rn = 1 then m.name end) as first_bidder,
max( case when rn = 2 then b.max_bid end) as second_max_bid,
max( case when rn = 2 then m.name end ) as second_bidder
from
stock s
left join
(select * from
(select *,
(@rn := if(@lot_id = lot_id, @rn+1,
if( @lot_id := lot_id, 1, 1))) as rn
from bids cross join
(select @rn := 0, @lot_id := -1) param
order by lot_id, max_bid desc
) t
where rn <= 2) b
on s.lot_number = b.lot_id
left join members m
on b.bidder_id = m.member_id
group by s.lot_number, s.reserve, s.current_bid
order by s.lot_number