如何理解PRIMARY KEY和'('在MySQL表创建中的名称?

问题描述 投票:0回答:2

如何理解MySQL中这样的句子名称'test_id'?

CREATE TABLE test(id INT, PRIMARY KEY test_id(id));

在学习MySQL的时候,我碰巧读到了这样一句话:

CREATE TABLE test(id INT, PRIMARY KEY test_id(id));

在我的MACOS 10.14 [email protected] shell中,我试图省略'test_id'来创建表,我使用'DESC test;'声明,发现我创建的两个表没有区别。

  1. 'test_id'的声明:
mysql> CREATE TABLE test(id INT, PRIMARY KEY test_id(id));
Query OK, 0 rows affected (0.01 sec)

mysql> DESC test;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.01 sec)
  1. 没有'test_id'的声明:
mysql> CREATE TABLE test2(id INT, PRIMARY KEY (id));
Query OK, 0 rows affected (0.01 sec)

mysql> DESC test2;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)
mysql
2个回答
3
投票

documentation说的是:

PRIMARY KEY的名字总是PRIMARY

基本上,MySQL接受这个名字(因为它想要很好),然后默默地丢弃它(因为你毕竟不能设置自己的名字)。用另一个例子更好地发现:

mysql> CREATE TABLE test(id INT, foo INT, PRIMARY KEY this_is_ignored (id), KEY this_is_kept (foo));
Query OK, 0 rows affected (0.02 sec)

mysql> show keys from test;
+-------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name     | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| test  |          0 | PRIMARY      |            1 | id          | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
| test  |          1 | this_is_kept |            1 | foo         | A         |           0 |     NULL | NULL   | YES  | BTREE      |         |               |
+-------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
2 rows in set (0.00 sec)

(Qazxswpoi)。


1
投票

这两个陈述都在做同样的工作。他们正在创造这张桌子。但在第一个SQL中

Fiddle

它创建一个名为test的表,并为主键约束命名为'test_id'。

在第二个SQL的情况下

CREATE TABLE test(id INT, PRIMARY KEY test_id(id))

它创建一个名为test的表,并为主键约束生成一个随机名称。

使用以下查询并检查使用两个表创建的约束

CREATE TABLE test2(id INT, PRIMARY KEY (id))
© www.soinside.com 2019 - 2024. All rights reserved.