How to Generate Random number without repeat in database using PHP?

后端 未结 11 2076
清酒与你
清酒与你 2020-12-02 11:15

I would like to generate a 5 digit number which do not repeat inside the database. Say I have a table named numbers_mst with field named my_number

11条回答
  •  生来不讨喜
    2020-12-02 11:52

    NOTE: The other solutions posted will work only if the column is configured as NOT NULL. If NULL, it'll just return no results. You can fix the query like this:

    SELECT random_num
    FROM (
      SELECT FLOOR(RAND() * 99999) AS random_num
    ) AS numbers_mst_plus_1
    WHERE random_num NOT IN (SELECT my_number FROM numbers_mst WHERE my_number IS NOT NULL)
    LIMIT 1
    

    ... The ...WHERE my_number IS NOT NULL is necessary!

    EDIT: I just wanted to mention that I intentionally removed the inner SELECT's table name because it didn't seme necessary and seemed to break if there was no data in the table yet? However, maybe this was intentionally included? — Please clarify or comment for everyone, thanks.

提交回复
热议问题