gpt4 book ai didi

mysql - sql 如果存在则插入,如果不存在则插入

转载 作者:行者123 更新时间:2023-11-29 17:47:07 24 4
gpt4 key购买 nike

如果我的表“current_schedule”中已经有给定日期的数据,我需要获取该“id”并插入到另一个具有该“id”的表“统计”中。如果没有,我需要创建它,然后使用创建的“id”插入。我几乎完成了:

   cursor.execute("SELECT id FROM current_schedule WHERE date = '{}'".format(lessondate))
idforme = cursor.fetchone()
if cursor.fetchone():
idforme = idforme[0]
if flag == str_to_bool('true'):
cursor.execute("INSERT INTO statistic (id_student, id_current_schedule,here) \
VALUES ('{}','{}',1)".format(id_student,idforme))
if flag == str_to_bool('false'):
cursor.execute("INSERT INTO statistic (id_student, id_current_schedule,here) \
VALUES ('{}','{}',0)".format(id_student,idforme))
else:
cursor.execute("INSERT INTO current_schedule (id_schedule, date) VALUES ('{}','{}')".format(id_schedule,lessondate))
mysql.connection.commit()
if flag == str_to_bool('true'):
cursor.execute("INSERT INTO statistic (id_student, id_current_schedule,here) \
VALUES ('{}',LAST_INSERT_ID(),1)".format(id_student))
if flag == str_to_bool('false'):
cursor.execute("INSERT INTO statistic (id_student, id_current_schedule,here) \
VALUES ('{}',LAST_INSERT_ID(),0)".format(id_student))
mysql.connection.commit()

但问题是它在“current_schedule”中创建了两次新数据,并且只有在那之后才开始将已创建的“id”(第一个)数据插入“statistic”中。

最佳答案

尝试一下怎么样,因为它基本上是相同的查询:

else:
cursor.execute("INSERT INTO current_schedule (id_schedule, date) VALUES ('{}','{}')".format(id_schedule,lessondate))
mysql.connection.commit()
flagNum = 0 if flag == str_to_bool('false') else 1
cursor.execute("INSERT INTO statistic (id_student, id_current_schedule,here) \
VALUES ('{}',LAST_INSERT_ID(),{})".format(id_student, flagNum))
mysql.connection.commit()

关于mysql - sql 如果存在则插入,如果不存在则插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49716875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com