【发布时间】:2018-09-17 21:41:10
【问题描述】:
如果我的表“current_schedule”中已经有给定日期的数据,我需要将该“id”插入到另一个具有该“id”的表“statistic”中。如果我没有,我需要创建它,然后使用创建的“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”中。
【问题讨论】:
-
你确定
flag永远只是'true'或'false'?您能否尝试使用else而不是if flag == str_to_bool('false'):,看看是否在第一次尝试时在statistic中创建了某些内容? -
@Nick 我已经通过添加第一个 if 条件 'idforme' 而不是 cursor.fetchone 来解决它
标签: mysql sql mysql-python