unique.md 790 字节
Newer Older
M
index  
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 唯一约束

Goods 表结构如下:

```mysql
create table goods(
    id int primary key auto_increment,
    category_id int,
    name varchar(256),
    price decimal(12, 4),
    stock int,
    upper_time timestamp
)
```

Joe 需要确保同一个类型下没有重名的商品,他应该怎么做?

M
Mars Liu 已提交
18 19
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill)

M
index  
Mars Liu 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
## 答案

```mysql
alter table goods add unique index (category_id, name);
```

## 选项

### A

```mysql
alter table goods add index (category_id, name);
```

### B

```mysql
alter table goods add unique index (category_id + name);
```

### C

```mysql
alter table goods add unique index (concat(category_id, name));
```