2015-05-13 36 views
0

我的拍賣SQL - 拍賣 - 列出多個最高投標

CREATE TABLE Auction (
    id SERIAL PRIMARY KEY, 
    owner_id INTEGER REFERENCES Registered(user_id), 
    title VARCHAR(50) NOT NULL, 
    starting_bid NUMERIC(10,2) NOT NULL CHECK (starting_bid >= 0), 
    starting_time TIMESTAMP NOT NULL, 
    ending_time TIMESTAMP NULL CHECK (starting_time < ending_time), 
    status_id INTEGER REFERENCES AuctionStatus(id), 
    winner_id INTEGER REFERENCES Registered(user_id) NULL, 
    highest_bid NUMERIC(10,2) NOT NULL 
); 

我的出價

CREATE TABLE Bid (
    id SERIAL PRIMARY KEY, 
    user_id INTEGER REFERENCES Registered(user_id), 
    auction_id INTEGER REFERENCES Auction(id), 
    bid_value NUMERIC(10,2) CHECK (VALUE > 0), 
    creation_date TIMESTAMP NOT NULL, 
    valid BOOLEAN DEFAULT TRUE NOT NULL 
); 

我希望用戶能夠列出所有在那裏他出價+他的出價最高的競價每次拍賣。

我開始與

SELECT auction.id, auction.title, auction.highest_bid, bid.bid_value 
FROM auction 
JOIN bid 
ON auction.id = bid.auction_id 
WHERE bid.owner_id = :userID AND bid.active = TRUE AND auction.status_id = 1 

列出他所有的投標,但我無法從這裏向前移動,以獲取用戶的每次拍賣的最高成交價。

回答

2
SELECT distinct on (auction.id) auction.id, auction.title, auction.highest_bid, bid.bid_value 
FROM auction 
JOIN bid 
ON auction.id = bid.auction_id 
WHERE bid.owner_id = :userID AND bid.active = TRUE AND auction.status_id = 1 
ORDER BY auction.id, bid.bid_value desc; 

欲瞭解更多信息,請參閱:

Select first row in each GROUP BY group?

「DISTINCT條款」 從 http://www.postgresql.org/docs/current/static/sql-select.html

+0

我看到的段落。我記得DISTINCT,但我忘記了ORDER BY。 – Crowley