Search code examples
mysqlcountrecords

same query returnd different number of records every time


This query result every time differently:

update product_models
  set category_id = (select id from categories order by RAND() limit 1)

Different counts repeatedly: 884 record(s) were affected
878 record(s) were affected
877 record(s) were affected
892 record(s) were affected
893 record(s) were affected
883 record(s) were affected
885 record(s) were affected

How come?

extra info


in the categories there are 22 rows
in the product models - 900
in the products - 600
the sub query has no conditions, no joins and always return a single row.
the main query also has no conditions or joins, so it should also return a fixed number.

So, every execution should return 900 product models, and each p.m should be updated by the subquery


Solution

  • Assuming that each time that you run the query the data is identical, the cause is that rows aren't counted as affected if the data doesn't change. So if 5 is selected as the random ID, rows that already have 5 for the category_id aren't counted.