简体   繁体   English

MySQL CREATE TABLE语句中的PRIMARY KEY定义

[英]PRIMARY KEY definition in MySQL CREATE TABLE statement

What's the difference between this code: 这段代码有什么区别:

CREATE TABLE samples (
  sampleid INT(11) NOT NULL AUTO_INCREMENT,
  sampledate DATE NOT NULL,
  location VARCHAR(25) NOT NULL,
  PRIMARY KEY (sampleid)
)
ENGINE=InnoDB;

and this: 还有这个:

CREATE TABLE samples (
  sampleid INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  sampledate DATE NOT NULL,
  location VARCHAR(25) NOT NULL,
)
ENGINE=InnoDB;

code? 码?

So a separate PRIMARY KEY statement or as part of a column definition. 所以单独的PRIMARY KEY语句或作为列定义的一部分。 Same question for UNIQUE INDEX and UNIQUE keyword in column definition. 列定义中UNIQUE INDEX和UNIQUE关键字的相同问题。

The second syntax is merely a shortcut allowing you to specify the column and add an index on it in a single clause. 第二种语法只是一个快捷方式,允许您指定列并在单个子句中为其添加索引。

This works out fine in cases where you simply want to create a column and add an index on it. 如果您只想创建一个列并在其上添加索引,这样就可以正常工作。

You'll need to use the first syntax if you want to do something more complicated, such as adding an index based on multiple columns rather than a single column, or if you are adding or changing an index on an existing column; 如果要执行更复杂的操作,则需要使用第一种语法,例如,基于多列而不是单列添加索引,或者在现有列上添加或更改索引; that is, you are not creating the column and the index on it at the same time. 也就是说,您不是同时在其上创建列和索引。

MySQL allows uses the PRIMARY KEY directive to allow you to set the Primary Key dynamically. MySQL允许使用PRIMARY KEY指令允许您动态设置主键。 Supplying PRIMARY KEY as an argument to the constructor can only be called on creating the column. 提供PRIMARY KEY作为构造函数的参数只能在创建列时调用。 PRIMARY KEY(X), PRIMARY KEY(Y), PRIMARY KEY(Z) allows for changing the primary keys on subsequent queries. PRIMARY KEY(X),PRIMARY KEY(Y),PRIMARY KEY(Z)允许在后续查询中更改主键。

The way I see it is.. The first method is used to create composite keys. 我看到它的方式是..第一种方法用于创建复合键。 While the second method (more readable to me) is primarily used if there is only primary key in the table. 虽然表中只有主键,但主要使用第二种方法(对我来说更易读)。

The second method cannot be used if you want to implement composite key 如果要实现组合键,则不能使用第二种方法

There are many ways to skin a cat and above 2 examples are just 2 of them. 皮肤猫的方法有很多种,其中2个例子只有2个。 They are identical. 它们完全相同。 There's no difference. 没有区别。

They are literally the same. 它们字面意思相同。 Here is a quick site that shows you the different ways (3) to do it. 这是一个快速网站,向您展示了不同的方式(3)。 http://www.java2s.com/Code/SQL/Key/Defineanduseprimarykey.htm http://www.java2s.com/Code/SQL/Key/Defineanduseprimarykey.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM