Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如果表为空或满足联接条件,则插入_Mysql_Sql - Fatal编程技术网

Mysql 如果表为空或满足联接条件,则插入

Mysql 如果表为空或满足联接条件,则插入,mysql,sql,Mysql,Sql,对于核心sqler来说,这是一个很好的难题 表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, cr

对于核心sqler来说,这是一个很好的难题

表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; 
给定拍卖,如果满足以下条件之一,用户可以对其进行出价:

  • 上一次出价创建时间不到拍卖时间秒
  • 此次拍卖没有出价
糟糕的说法是:这是一个游戏,最后一个竞价用户在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、拍卖id)
选择1,a.id
从作为a的拍卖,到作为b的出价
其中a.id=b.id
并且a.user\u id为空
a.id=1
和(UNIX_TIMESTAMP()-b.created_at)

它可以工作,但我不知道如何将“给定拍卖id是否存在出价”逻辑放在里面。

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

OR NOT EXISTS (SELECT * FROM bids WHERE auction_id = ?)

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

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
插入投标(用户id、拍卖id)
选择1,a.id
从拍卖到拍卖
左外连接为b
在a.id=b.id上
和(UNIX_TIMESTAMP()-b.created_at)
谢谢你,brian,但是如果子查询在其中,查询会是原子的吗?可能不会,但我认为连接也不会是原子的。您可能必须首先锁定表。这里的解决方案(参数的问号):插入投标(user_id,auction_id)SELECT?,a.id从拍卖中作为左外部连接投标为b ON a.id=b.auction_id,其中a.user_id为NULL,a.id=?和((UNIX_TIMESTAMP()-b.created_at)