MySQL insert varchar value into int auto increment column

2skhul33  于 2023-05-21  发布在  Mysql
关注(0)|答案(2)|浏览(124)

我注意到在项目暂存服务器上奇怪的MySQL行为。给出:

create table test_table
(
    id   int auto_increment,
    name varchar(64) not null,
    constraint test_table_pk
        primary key (id)
);

insert into test_table (id, name)
VALUES (3, 'value 3');
insert into test_table (id, name)
VALUES (5, 'value 5');
insert into test_table (id, name)
VALUES ('value 6 id', 'value 6');

select *
from test_table;

结果:

mysql> select * from test_table;
+----+---------+
| id | name    |
+----+---------+
|  3 | value 3 |
|  5 | value 5 |
|  6 | value 6 |
+----+---------+
2 rows in set (0.01 sec)

前两个insert语句按预期正常工作。第三个背后的魔力是什么?它的工作,似乎不正确的类型值被替换为自动增量值。我正在尝试创建DB服务器的Docker版本。但我找不到什么配置选项来启用此行为。第三个insert语句被docker DB示例拒绝,并显示错误消息:

Incorrect Integer value: 'value 6 id' for column 'id'
mysql> SHOW VARIABLES LIKE 'version';
+---------------+-----------+
| Variable_name | Value     |
+---------------+-----------+
| version       | 5.7.27-30 |
+---------------+-----------+
1 row in set (0.01 sec)

更新
在临时服务器上:

show variables like '%sql_mode%';

退货:

IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

我的docker-compose.yaml

version: "3.8"
services:
 db:
    image: percona/percona-server:5.7.27
    volumes:
      -db-data:/var/lib/mysql
    env_file:
      - ./db.env
    command:
      --sql_mode=IGNORE_SPACE,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
    ports:
      - "3306:3306"
  flyway:
    image: flyway/flyway:7.15.0
    command: migrate
    volumes:
      - ./../../sql/migrations:/flyway/sql
      - ./flyway/conf:/flyway/conf
    depends_on:
      -db
volumes:
  db-data:

有什么想法吗?谢谢

fwzugrvs

fwzugrvs1#

您启用了STRICT_TRANS_TABLES,导致无效数据值被拒绝,应将其从列表中删除:

SET sql_mode='IGNORE_SPACE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

Demo here

laximzn5

laximzn52#

这与sql_mode有关。您可以检查两个数据库示例的sql_mode参数来找出其中的秘密。
show variables like '%sql_mode%';

相关问题