1

I wanna create a mysql update only if the table does not contain the specified value(if player have empty slot)

My Idea:

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

I hope this can be only one mysql question

1 Answer 1

1

One way to do this is using the anti-join pattern, e.g.

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

The LEFT JOIN looks for a matching row, but if no matching row is found then MySQL will generate a row with all NULL values. We can filter out any rows that matched using the q.uid IS NULL predicate, so we will only get rows where there was no match.

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
Sign up to request clarification or add additional context in comments.

2 Comments

spencer7593 this not works :( I got an error in my mysql and SQL Fiddle (Schema Creation Failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE player_items)
I had the SET clause is in the wrong position, it belongs before the WHERE clause. I've modified the query, and it seems to work for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.