Skip to content

mysql_insert_id() incompatible between tidb and mysql  #55965

@mzhang77

Description

@mzhang77

1. Minimal reproduce step (Required)

package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
)

func executeSQL(db *sql.DB, sql string) sql.Result {

	result, err := db.Exec(sql)
	if err != nil {
		log.Fatal("Error executing query:", err)
	}
	return result
}

func insertRow(db *sql.DB, a, b int) int {

	insertQuery := "INSERT INTO tb (a, b) VALUES (?, ?) ON DUPLICATE KEY UPDATE b = VALUES(b)"
	result, err := db.Exec(insertQuery, a, b)
	if err != nil {
		log.Fatal("Error executing insert query:", err)
	}

	// Get the last inserted ID
	lastInsertId, err := result.LastInsertId()
	if err != nil {
		log.Fatalf("Error fetching LastInsertId: %v", err)
	}

	return int(lastInsertId)
}

func main() {
	// Define the MySQL connection string
	dsn := "root@tcp(127.0.0.1:4000)/test"
    //dsn := "root@tcp(127.0.0.1:3306)/test"

	// Open a connection to the database
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("Error opening database connection: %v", err)
	}
	defer db.Close()

	// Test the connection
	err = db.Ping()
	if err != nil {
		log.Fatalf("Error connecting to the database: %v", err)
	}

	_ = executeSQL(db, "drop table if exists tb")

	_ = executeSQL(db, "create table tb(pk int primary key auto_increment, a int, b int, unique(a))")

	lastInsertId := insertRow(db, 1, 1)
	fmt.Printf("Last inserted ID: %d\n", lastInsertId)

	lastInsertId = insertRow(db, 2, 2)
	fmt.Printf("Last inserted ID: %d\n", lastInsertId)

	lastInsertId = insertRow(db, 1, 2)
	fmt.Printf("Last inserted ID: %d\n", lastInsertId)

}


// tiup playground v7.5.1:
// Last inserted ID: 1
// Last inserted ID: 2
// Last inserted ID: 0

// MySQL v8.0.23:
// Last inserted ID: 1
// Last inserted ID: 2
// Last inserted ID: 1

2. What did you expect to see? (Required)

The code should return same result from mysql and tidb

3. What did you see instead (Required)

// tiup playground v7.5.1:
// Last inserted ID: 1
// Last inserted ID: 2
// Last inserted ID: 0

// MySQL v8.0.23:
// Last inserted ID: 1
// Last inserted ID: 2
// Last inserted ID: 1

4. What is your TiDB version? (Required)

mysql> select @@version;
+--------------------+
| @@version          |
+--------------------+
| 8.0.11-TiDB-v7.5.1 |
+--------------------+
1 row in set (0.01 sec)

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions