sql insert如果存在则插入,如果不存在则插入

时间:2018-04-08 10:27:10

标签: mysql sql mysql-python

如果我的表'current_schedule'中的数据已经包含给定日期,我需要获取'id'并将INSERT插入到具有该'id'的另一个表'统计'中。如果我没有,我需要创建它然后INSERT创建'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'。

1 个答案:

答案 0 :(得分:0)

尝试这个怎么样,因为它的查询基本相同:

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()