这些FK定义是否等效?

时间:2019-05-25 09:04:48

标签: mysql sql foreign-keys schema ddl

以下两个address外键定义是否等效?我的意思是说,它们最终是否具有相同的有效数据库元素(索引,约束等)。我更喜欢后者,因为它是一种简写,而且不需要键入。

在这里显式创建地址索引和约束:

CREATE TABLE customer (
  customer_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
  first_name VARCHAR(45) NOT NULL,
  last_name VARCHAR(45) NOT NULL,
  PRIMARY KEY  (customer_id),
  KEY idx_fk_address_id (address_id),
  CONSTRAINT fk_customer_address FOREIGN KEY (address_id) REFERENCES address (address_id) ON DELETE RESTRICT ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

约束和索引也在这里创建吗?

CREATE TABLE customer (
  customer_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
  first_name VARCHAR(45) NOT NULL,
  last_name VARCHAR(45) NOT NULL,
  PRIMARY KEY  (customer_id),
  FOREIGN KEY (address_id) REFERENCES address (address_id) ON DELETE RESTRICT ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

还有其他需要注意的区别吗?

1 个答案:

答案 0 :(得分:2)

从功能的角度来看,这些声明是等效的。区别在于,第一个代码段设置了一个友好的名称,以后将更易于维护,而第二个代码段将创建一些自动生成的名称。