MySQL - 创建表时一起使用 "PRIMARY KEY"、 "UNIQUE KEY"和 "KEY"的含义

标签 mysql sql-server primary-key unique-key

谁能解释一下 PRIMARY KEYUNIQUE KEYKEY 的用途,如果它们放在一个 中的话MySQL 中的 CREATE TABLE 语句?

CREATE TABLE IF NOT EXISTS `tmp` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `tag` int(1) NOT NULL DEFAULT '0',
  `description` varchar(255),
  PRIMARY KEY (`id`),
  UNIQUE KEY `uid` (`uid`),
  KEY `name` (`name`),
  KEY `tag` (`tag`)
) ENGINE=InnoDB AUTO_INCREMENT=1 ;

如何将此查询转换为 MSSQL?

最佳答案

键只是一个普通的索引。一种过度简化的方法是将其想象成图书馆的卡片目录。它为 MySQL 指明了正确的方向。

唯一键也用于提高搜索速度,但它具有不能重复项的约束(没有两个 x 和 y,其中 x 不是 y 且 x == y)。

manual解释如下:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.

主键是一个“特殊”的唯一键。它基本上是一个唯一的键,除了它用于识别某些东西。

该手册解释了一般如何使用索引:here .

在 MSSQL 中,概念是相似的。有索引、唯一约束和主键。

未经测试,但我相信 MSSQL 等效项是:

CREATE TABLE tmp (
  id int NOT NULL PRIMARY KEY IDENTITY,
  uid varchar(255) NOT NULL CONSTRAINT uid_unique UNIQUE,
  name varchar(255) NOT NULL,
  tag int NOT NULL DEFAULT 0,
  description varchar(255),
);

CREATE INDEX idx_name ON tmp (name);
CREATE INDEX idx_tag ON tmp (tag);

编辑:上面的代码经过测试是正确的;但是,我怀疑这样做有更好的语法。自从我使用 SQL Server 以来已经有一段时间了,显然我已经忘记了很多:)。

关于MySQL - 创建表时一起使用 "PRIMARY KEY"、 "UNIQUE KEY"和 "KEY"的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10908561/

相关文章:

sql - SQL Server 中的 ISNULL 与 IS NULL

Mysql 查询选择行以及其他表上的匹配行

PHP PDO SQL 语法错误

mysql - SQL中对列的操作

sql-server - 如何压缩查询结果?

sql - T-SQL - 转换数据类型时出错 - 显示有问题的行

arrays - 可以使用 Realm 和快速删除基于主键的行吗?

MySQL。同一字段的 UNIQUE 和 PRIMARY KEY 约束

database - 卡宴,Postgres : primary key generation

mysql - 如何搜索两个表