我有一个小型的竞价系统,我正用于幻想拍卖。我正在尝试使用以下查询来提取每个玩家的最高出价。但是,它实际上并没有给我最高出价,只是给了我输入数据库的第一个。
SELECT Bid.id FROM bids AS Bid
WHERE Bid.active =1
GROUP BY player_id HAVING MAX( Bid.amount )
以下是Bid表格布局,如果有帮助:
CREATE TABLE IF NOT EXISTS `bids` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`user_id` int(10) NOT NULL,
`player_id` int(10) NOT NULL,
`amount` int(6) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`winning_bid` int(1) NOT NULL DEFAULT '0',
`active` int(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
答案 0 :(得分:3)
select max(amount), player_id from bids
where active = 1
group by player_id
order by 1 desc;
答案 1 :(得分:1)
Ever子句需要进行布尔检查。所以,你的having MAX(Bid.Amount)
并没有按照你的想法去做。你(理论上)想要的是having Bid.Amount = MAX(Bid.Amount)
,虽然这会导致更多问题,因为你应该在技术上对Bid.Amount
进行分组,因为它存在于聚合之外,而这根本不是你的意思。
(警告,未经测试的查询,但它们应该非常接近)
如果您只想要单个玩家的最高出价,那么您实际应该做的非常简单,按出价按降序排序时选择第一条记录:
select
b.id
from
bids b
where
b.active = 1
and b.player_id = @playerID
order by
b.bids desc
limit 1
如果你想要所有玩家,这个查询仍然给你起点,你只需要将每个player_id
传递给它:
select
bid.playerID,
bid.id
from
bids bid
join (
select
b.id
from
bids b
where
b.active = 1
order by
b.bids desc
limit 1
) maxbid on maxbid.playerid = bid.playerid
答案 2 :(得分:0)
你可以尝试:
SELECT Bid.id
FROM bids AS Bid,
(SELECT player_id, MAX(amount) AS player_max
FROM bids
WHERE active=1
GROUP BY player_id) AS max_amounts
WHERE Bid.player_id = max_amounts.player_id
AND Bid.amount = max_amounts.amount;
但是,我不确定在发生关系时的行为。
答案 3 :(得分:0)
或者,Khorkrak的另一种选择(其中也可以使用):
SELECT Bid.id FROM bids AS Bid
LEFT JOIN bids as x
ON x.amount > Bid.amount
AND x.active = 1
AND x.player_id = Bid.player_id
WHERE Bid.active = 1 AND x.player_id IS NULL
GROUP BY player_id
答案 4 :(得分:0)
这是一个使用行级来查找最高出价的人。你也可以使用这样的东西来找到第二高,第三高等......
SELECT id, player_id, amount
FROM
(
select b.id, b.player_id, b.amount, count(*) as num
from bids b left outer join bids b2
on b.player_id = b2.player_id
AND b.amount = b2.timestamp
AND b.active = 1
group by b.id, b.player_id, b.amount
)
r
WHERE
num = 1