2010-06-05 68 views
0

我有一個小招標系統,我正在使用幻想拍賣草案。我正在嘗試使用下面的查詢來提高每個玩家的最高出價。但是,它實際上並沒有給我最高出價,它只是給我輸入數據庫的第一個。MySQL查詢:獲勝拍賣出價

SELECT Bid.id FROM bids AS Bid 
WHERE Bid.active =1 
GROUP BY player_id HAVING MAX(Bid.amount) 

這裏的投標表格佈局,在情況下,它可以幫助:

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 ; 

回答

3
select max(amount), player_id from bids 
where active = 1 
group by player_id 
order by 1 desc; 
1

曾經條款需要做一個布爾檢查。所以,你的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 
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; 

我不能確定的關係的情況下的行爲,雖然。

+0

我認爲如果出現平局,最早的出價應該會贏。 – 2010-06-05 15:38:19

0

或者,Khorkrak的(這ofcourse也工作)的一種替代:

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 
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