1

铁杆 SQLers 的好拼图。

2张桌子:拍卖和出价。

CREATE TABLE auctions
(
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
created_at INT,
timer INT DEFAULT 10,
user_id BIGINT UNSIGNED
)ENGINE=InnoDB;

CREATE TABLE bids
(
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
created_at INT,
user_id BIGINT UNSIGNED,
auction_id BIGINT UNSIGNED
)ENGINE=InnoDB; 

给定拍卖,如果满足以下条件之一,用户可以对其出价:

  • 上次出价的创建时间少于 auction.timer 秒前
  • 拍卖没有出价

简而言之:这是一个在 x 秒内没有任何人关注的最后一个出价用户赢得拍卖的游戏。

这里不允许交易。

这是我的尝试:

INSERT INTO bids (user_id, auction_id) 
SELECT 1, a.id
FROM auctions AS a, bids AS b
WHERE a.id = b.auction_id
AND a.user_id IS NULL
AND a.id = 1
AND (UNIX_TIMESTAMP() - b.created_at) < a.timer
LIMIT 1

它有效,但我不知道如何将“或给定拍卖 ID 不存在出价”逻辑放入其中。

4

2 回答 2

1

您可以使用子查询来确定拍卖中是否有任何出价。也许是这样的:

OR NOT EXISTS (SELECT * FROM bids WHERE auction_id = ?)
于 2013-10-17T20:43:07.080 回答
1

如果我对您的理解正确,您需要外部连接(可选)出价。像这样:

INSERT INTO bids (user_id, auction_id) 
SELECT 1, a.id
FROM auctions AS a
left outer join bids AS b
ON a.id = b.auction_id
AND (UNIX_TIMESTAMP() - b.created_at) < a.timer
where
(a.user_id IS NULL
AND a.id = 1

) OR
b.id IS NULL     --this will be true if there is no bid present
LIMIT 1
于 2013-10-17T20:43:45.477 回答