jeudi 18 juin 2020

Why does this UPDATE affect 2 rows when its WHERE specifies only one?

Please examine the following UPDATE statement that I'm running in MySQL 8.0, against the Sakila sample database:

UPDATE `film`
SET
    `original_language_id` = FLOOR(1 + (RAND() * 6))
WHERE
    `film_id` = FLOOR(1 + (RAND() * 1000));

The idea is to update a random row from film to have the original_language_id column key for that row have a value between 1 and 6.

The film table has 1000 rows in it with PKs from 1 to 1000. The original_language_id column is a foreign key to the language table. The language table has 6 rows in it with PKs from 1 to 6.

The above UPDATE statement is deemed unsafe by MySQL (Error 1175). (I'd love to know why, but that's not my question). So to force the statement to run, I precede it with: SET SQL_SAFE_UPDATES = 0;.

When I then run the UPDATE statement I expect to see in the Output window:

1 row(s) affected Rows matched: 1 Changed: 1 Warnings: 0

But instead I sometimes get 0 rows affected, sometimes 1 and sometimes 2!

My question is why doesn't this UPDATE statement consistently affect one and only one row?

PS - Please avoid comments on whether the query makes sense to you or not and/or on the prudence of disabling safe update mode. The query is an exercise for learning purposes and I'm fully aware of the importance of said mode. Thank you.




Aucun commentaire:

Enregistrer un commentaire