我只想在表不包含指定值时创建一个 mysql 更新(如果玩家有空槽)
我的想法:
update player_items
set slot=20
where id=0
and uid=2
and (SELECT COUNT(*)
FROM player_items
WHERE slot=12 and uid=2) = 0;
我希望这只能是一个mysql问题
我只想在表不包含指定值时创建一个 mysql 更新(如果玩家有空槽)
我的想法:
update player_items
set slot=20
where id=0
and uid=2
and (SELECT COUNT(*)
FROM player_items
WHERE slot=12 and uid=2) = 0;
我希望这只能是一个mysql问题
一种方法是使用反连接模式,例如
UPDATE player_items p
LEFT
JOIN ( SELECT uid
FROM player_items
WHERE slot = 12
AND uid = 2
LIMIT 1
) q
ON q.uid = p.uid
SET p.slot = 20
WHERE p.id = 0
AND p.uid = 2
AND q.uid IS NULL
LEFT JOIN 寻找匹配的行,但如果没有找到匹配的行,那么 MySQL 将生成一个包含所有 NULL 值的行。我们可以使用谓词过滤掉任何匹配的行q.uid IS NULL
,所以我们只会得到不匹配的行。
mysql> UPDATE player_items p
-> LEFT
-> JOIN ( SELECT uid
-> FROM player_items
-> WHERE slot = 12
-> AND uid = 2
-> LIMIT 1
-> ) q
-> ON q.uid = p.uid
-> SET p.slot = 20
-> WHERE p.id = 0
-> AND p.uid = 2
-> AND q.uid IS NULL
-> ;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0