mysql建表时如何加约束
时间: 2023-06-29 17:07:11 浏览: 89
在 MySQL 中,可以使用以下语法来为表添加约束:
1. PRIMARY KEY 约束:用于定义主键。语法如下:
```
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
PRIMARY KEY (one or more columns)
);
```
示例:
```
CREATE TABLE users (
user_id INT AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (user_id)
);
```
2. UNIQUE 约束:用于定义唯一键。语法如下:
```
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
UNIQUE (one or more columns)
);
```
示例:
```
CREATE TABLE users (
user_id INT AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (user_id)
);
```
3. FOREIGN KEY 约束:用于定义外键。语法如下:
```
CREATE TABLE table_name1 (
column1 datatype constraints,
column2 datatype constraints,
...
PRIMARY KEY (one or more columns)
);
CREATE TABLE table_name2 (
column1 datatype constraints,
column2 datatype constraints,
...
FOREIGN KEY (column_name) REFERENCES table_name1(column_name)
);
```
示例:
```
CREATE TABLE departments (
department_id INT AUTO_INCREMENT,
department_name VARCHAR(50) NOT NULL,
location VARCHAR(100) NOT NULL,
PRIMARY KEY (department_id)
);
CREATE TABLE employees (
employee_id INT AUTO_INCREMENT,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id),
PRIMARY KEY (employee_id)
);
```
以上是 MySQL 中常用的约束类型,可以根据需求选择适合的约束类型。
阅读全文