谁能解释一下 PRIMARY KEY
、UNIQUE KEY
和 KEY
的用途,如果它们放在一个 中的话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/