mysql5.7 ON DUPLICATE KEY UPDATE语法将更新额外的列

时间:2019-04-12 04:02:43

标签: mysql go

mysql5.7'ON DUPLICATE KEY UPDATE'语法将更新额外的列,即使您尚未更新

使用'insert ... ON DUPLICATE KEY UPDATE ...'更新some_data = VALUES(some_data),它也会更新created_at列

result, err := DB.Exec("INSERT INTO `test_duplicate_key_bug_table`(some_data,created_at) VALUES(?,?)", "test data", createdAt)
    require.NoError(t, err)
    id, err := result.LastInsertId()
    require.NoError(t, err)
    // mysql's timestamp only storage second's level date, re-find it's real datetime
    row := DB.QueryRow("SELECT created_at FROM `test_duplicate_key_bug_table` WHERE id=? LIMIT 1", id)
    var oldCreatedAt time.Time
    err = row.Scan(&oldCreatedAt)
    require.NoError(t, err)

    result, err = DB.Exec("INSERT INTO `test_duplicate_key_bug_table`(id,some_data,created_at) VALUES(?,?,?) ON DUPLICATE KEY UPDATE some_data = VALUES(some_data)", id, "test data again", time.Now())
    require.NoError(t, err)

    row = DB.QueryRow("SELECT some_data,created_at FROM `test_duplicate_key_bug_table` WHERE id=? LIMIT 1", id)
    var newCreatedAt time.Time
    var newData string
    err = row.Scan(&newData, &newCreatedAt)
    require.NoError(t, err)

    fmt.Printf("old time %s \n", oldCreatedAt)
    fmt.Printf("new time %s \n", newCreatedAt)
    fmt.Printf("new data %s \n", newData)

输出:

old time 2019-04-12 03:29:17 +0000 UTC 
new time 2019-04-12 03:29:27 +0000 UTC 
new data test data again 

但仅更新id = VALUES(id),效果很好

result, err := DB.Exec("INSERT INTO `test_duplicate_key_bug_table`(some_data,created_at) VALUES(?,?)", "test data", createdAt)
    require.NoError(t, err)
    id, err := result.LastInsertId()
    require.NoError(t, err)
    // mysql's timestamp only storage second's level date, re-find it's real datetime
    row := DB.QueryRow("SELECT created_at FROM `test_duplicate_key_bug_table` WHERE id=? LIMIT 1", id)
    var oldCreatedAt time.Time
    err = row.Scan(&oldCreatedAt)
    require.NoError(t, err)

    result, err = DB.Exec("INSERT INTO `test_duplicate_key_bug_table`(id,some_data,created_at) VALUES(?,?,?) ON DUPLICATE KEY UPDATE id = VALUES(id) ", id, "test data again", time.Now())
    require.NoError(t, err)

    row = DB.QueryRow("SELECT some_data,created_at FROM `test_duplicate_key_bug_table` WHERE id=? LIMIT 1", id)
    var newCreatedAt time.Time
    var newData string
    err = row.Scan(&newData, &newCreatedAt)
    require.NoError(t, err)

    fmt.Printf("old time %s \n", oldCreatedAt)
    fmt.Printf("new time %s \n", newCreatedAt)
    fmt.Printf("new data %s \n", newData)

输出:

old time 2019-04-12 03:29:17 +0000 UTC 
new time 2019-04-12 03:29:17 +0000 UTC 
new data test data 

我正在使用docker's mysql

full example code

我想这是“ github.com/go-sql-driver/mysql”驱动程序问题

0 个答案:

没有答案