使用 LAST_INSERT_ID() 将最后创建的 auto_increment 值插入 table

Inserting last created auto_increment value into the table using LAST_INSERT_ID()

我有一个table的区域,里面可能有很多区。创建 table 时,我已将区域的 ID 设置为自动递增。

我已经尝试了使用 LAST_INSERT_ID() 在互联网上找到的所有解决方案,但都行不通。我收到 LAST_INSERT_ID() 未定义、语法不正确或不同步错误的错误。

我正在使用 python 和 mysql

cur.execute('''
            INSERT IGNORE INTO area1_tb (
            id,
            area1            
            ) VALUES (%s, %s)''',
            (None, area1,))


cur.execute('''INSERT IGNORE INTO district_tb (
            id,
            district1,
            area1_id
            ) VALUES (%s, %s, %s)''',
            (None, district1, SELECT LAST_INSERT_ID(),))

我需要将 area1_tb 中的 ID 链接到 district_tb 中的 area1_id,但我一直收到错误。

你非常接近。不要SELECT LAST_INSERT_ID()。只是使用它的价值。这是 MySQL 方言 SQL

中的一个函数

试试这个:

cur.execute('''
        INSERT IGNORE INTO area1_tb (
        id,
        area1            
        ) VALUES (%s, %s)''',
        (None, area1,))

cur.execute('''INSERT IGNORE INTO district_tb (
        id,
        district1,
        area1_id
        ) VALUES (%s, %s, LAST_INSERT_ID())''',
        (None, district1,))

而且,如果您想在单个区域中插入多个区域,请尝试将区域插入的 ID 存储在 MySQL 变量中,以便您可以重复使用它:

cur.execute('''
        INSERT IGNORE INTO area1_tb (
        id,
        area1            
        ) VALUES (%s, %s)''',
        (None, area1,))

cur.execute('SET @areaId := LAST_INSERT_ID()', Params=None)

cur.execute('''INSERT IGNORE INTO district_tb (
        id,
        district1,
        area1_id
        ) VALUES (%s, %s, @areaId)''',
        (None, district1,))
cur.execute('''INSERT IGNORE INTO district_tb (
        id,
        district1,
        area1_id
        ) VALUES (%s, %s, @areaId)''',
        (None, district2,))
cur.execute('''INSERT IGNORE INTO district_tb (
        id,
        district1,
        area1_id
        ) VALUES (%s, %s, @areaId)''',
        (None, district3,))

后续插入会覆盖 LAST_INSERT_ID(),因此您需要保存它以便重新使用。