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

标签 mysql sql mysql-python

如果我的表“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/

相关文章:

python - 无法获取 python 元组作为 WHERE IN SQL 子句中的输入?

php - 我如何在mysql中使用函数

MySQL语句错误使用 'Limit'

mysql - 选择带有字符串列的特定输出

mysql - 帮助 mysql 触发器(插入前检查值)

sql - Closure Table INSERT 语句包括水平/距离列

python - mysql-python 安装错误 : Cannot open include file 'config-win.h'

mysql - NPM mysql模块中的connect方法是否阻塞?

sql - Linux Sqliteman 安装后所有按钮和选项卡都显示为禁用,需要配置帮助吗?

python - 如何在数据库中存储实时聊天消息?