UNIQUE、UNIQUE KEY 和 CONSTRAINT 'name' 之间有什么区别?独特的?
我想在 MySQL 中创建一个基本的 users
表。
我不希望数据库中出现重复的电子邮件或重复的用户名。
- 创建表时防止这种情况的最佳方法是什么?
- 以下有什么区别:
1. UNIQUE(用户名),UNIQUE(电子邮件),
2. UNIQUE KEY(用户名),UNIQUE KEY(电子邮件),
3. CONSTRAINT ucons_login UNIQUE(用户名,电子邮件),
我认为其中一些是同义的,但我一直在网上阅读相互冲突的信息并寻求确认。
我希望有人可以提供帮助。
SQL:
CREATE TABLE users (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(30) NOT NULL,
pass CHAR(40) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
registration_date DATETIME NOT NULL,
user_level TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
active CHAR(32),
PRIMARY KEY (user_id),
UNIQUE (username),
UNIQUE (email),
INDEX login (email, pass),
INDEX full_name (last_name, first_name)
) ENGINE=INNODB;
I have a basic users
table I want to create in MySQL.
I do not want duplicate emails or duplicate usernames appearing in the database.
- What is the best way of preventing this upon table creation?
- And what is the difference between the following:
1.UNIQUE (username), UNIQUE (email),
2.UNIQUE KEY (username), UNIQUE KEY (email),
3.CONSTRAINT ucons_login UNIQUE (username, email),
I assume some of these are synonymous, yet I've been reading conflicting information online and was seeking confirmation.
I hope someone can assist.
The SQL:
CREATE TABLE users (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(30) NOT NULL,
pass CHAR(40) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
registration_date DATETIME NOT NULL,
user_level TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
active CHAR(32),
PRIMARY KEY (user_id),
UNIQUE (username),
UNIQUE (email),
INDEX login (email, pass),
INDEX full_name (last_name, first_name)
) ENGINE=INNODB;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
1 和 2 是相同的 - 都创建两个唯一索引,每个索引一个。 #3 只在两个键上创建一个唯一索引,因此用户名和电子邮件的组合不能重复,但例如,只要使用不同的电子邮件,用户名就可以重复。
听起来你可能想要前两个中的任何一个。 UNIQUE 和 UNIQUE KEY 是等效的。
1 and 2 are identical - both create two unique indexes, one for each key. #3 only creates one unique index across both keys, so no combination of username and email can be duplicated, but for example, a username could be duplicated as long as a different email was used.
Sounds like you probably want either of the first two. UNIQUE and UNIQUE KEY are equivalent.
语法文档证明它们都是同义词:
[]
在此表示法中 (Wirth 的符号)表示可选元素They are all synonymous as evidenced by syntax documentation:
[]
in this notation (Wirth's notation) denote optional elements