我正在看这个Mysql问题link :
我无法重复该问题的答案中描述的行为。
我尝试使用不同长度的 CHAR 和 VARCHAR 列创建表,长度并不重要 - SHOW CREATE TABLE 始终返回我最初定义的数据类型。
所以 - 没有进行 CHAR->VARCHAR 切换。
以下问题的答案是否仅部分正确(我只讨论第 1 项和第 2 项)?
问: 当您创建一个表,然后在其上运行 SHOW CREATE TABLE 时,您有时会得到与您输入的结果不同的结果。MySQL 在您新创建的表中修改了什么?
A(据说):
长度小于 4 的 VARCHAR 变为 CHAR
长度超过 3 的 CHAR 变为 VARCHAR。
NOT NULL 被添加到声明为 PRIMARY KEY 的列
为每列指定默认值,例如 NULL
最佳答案
MySQL 手册中有一页可以回答您的一些问题:12.1.14.2. Silent Column Specification Changes .
引用与您在问题中发布的项目相对应的一些部分:
对于第 3 项:
Columns that are part of a
PRIMARY KEY
are madeNOT NULL
even if not declared that way.
关于varchar列的大小(但不完全是您的项目之一):
If strict SQL mode is not enabled, a VARCHAR column with a length specification greater than
65535
is converted toTEXT
, and aVARBINARY
column with a length specification greater than65535
is converted toBLOB
. Otherwise, an error occurs in either of these cases.
该页面以以下句子结尾:
To see whether MySQL used a data type other than the one you specified, issue a
DESCRIBE
orSHOW CREATE TABLE
statement after creating or altering the table.
所以我猜您可能会期望一些未列出的其他差异。
进行快速测试,这是一个创建表
语句:
create table test_2 (
id int primary key,
blah_vc varchar(2),
blah_c char(5)
) engine=InnoDb;
创建的表给出:
mysql> desc test_2;
+---------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| blah_vc | varchar(2) | YES | | NULL | |
| blah_c | char(5) | YES | | NULL | |
+---------+------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> show create table test_2;
+--------+--------------------------------------------+
| Table | Create Table |
+--------+--------------------------------------------+
| test_2 | CREATE TABLE `test_2` (
`id` int(11) NOT NULL,
`blah_vc` varchar(2) DEFAULT NULL,
`blah_c` char(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+--------+--------------------------------------------+
1 row in set (0.00 sec)
所以:
- 否:
varchar
尚未转换为char
- 否:
char
尚未转换为varchar
- 是:
not null
已添加到主键
- 嗯,那个很有趣:描述说它没有,
- 但是显示创建表表明它有...
- 无论如何:对于主键列来说,不能为空是有意义的。
- yes :
null
被指定为可以为 null 的列的默认值。
关于Mysql VARCHAR 到 CHAR 转换行为问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5436283/