【问题标题】:sql insert if exist and insert if notsql 如果存在则插入,如果不存在则插入
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    相关资源
    最近更新 更多