如何生成一个随机的“否”但它不应该存在于表中?

问题描述 投票:0回答:1

我需要帮助为我自己的项目创建代码。它就像一个注册站点副本,但使用的是 Python 和 MySQL。

我需要生成一个随机数并检查它是否已存在于表中,如果存在则生成另一个也不应该存在于表中的数字。

我编写了一个代码,我认为它非常基本且错误,但有点帮助,我只需要这样的代码。

import random
import mysql.connector

db = mysql.connector.connect(host="", user="", password="")
cur = db.cursor()

cur.execute("USE iscr")
r = random.randint(1,20)
print(r)
i = str(r)
cur.execute("SELECT sno FROM schedule")
x = str(cur.fetchall())
while i in x:
    if i in x:
        r = random.randint(1,20)
        print(r)
    else:
        print(r)
    break
mysql python-3.x random registration
1个回答
0
投票
insert into schedule (sno)
with recursive cte(sno) as (
   select 1
   union
   select sno+1 from cte where sno < 10
),
sno(sno) as (
  select c1.sno+c2.sno*10+c3.sno*100+c4.sno*1000+c5.sno*10000
  from cte as c1 cross join cte as c2 cross join cte as c3 cross join cte as c4 cross join cte as c5
)
select sno.sno
from sno left outer join schedule using (sno)
where schedule.sno is null
order by rand()
limit 1;
© www.soinside.com 2019 - 2024. All rights reserved.