Mysql更新如果(某些声明)

时间:2013-07-11 19:12:22

标签: mysql count

我只想在表中没有包含指定值的情况下创建一个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;

code in sqlfiddle

我希望这只能是一个mysql问题

1 个答案:

答案 0 :(得分:1)

一种方法是使用反连接模式,例如

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