gpt4 book ai didi

go - unique_index 和 unique 有什么区别?

转载 作者:IT王子 更新时间:2023-10-29 02:31:11 25 4
gpt4 key购买 nike

在GORM中unique_index和unique有什么区别?
我正在使用 MySQL 8.0,我找不到关于 unique_index 和 unique form 手册之间区别的描述。
来自 here ,请具体查看 EmailMemberNumber 字段:

Declaring Models

Models are usually just normal Golang structs, basic Go types, or pointers of them. sql.Scanner and driver.Valuer interfaces are also supported.

Model Example:

type User struct {
gorm.Model
Name string
Age sql.NullInt64
Birthday *time.Time
Email string `gorm:"type:varchar(100);unique_index"`
Role string `gorm:"size:255"` // set field size to 255
MemberNumber *string `gorm:"unique;not null"` // set member number to unique and not null
Num int `gorm:"AUTO_INCREMENT"` // set num to auto incrementable
Address string `gorm:"index:addr"` // create index with name `addr` for address
IgnoreMe int `gorm:"-"` // ignore this field
}

最佳答案

unique 是一个数据库约束(在这种情况下)防止多个记录具有相同的 MemberNumber 值。如果进行了这样的插入或更新,操作将不会成功并返回错误。

unique_index 将创建一个数据库索引,该索引还确保没有两个值可以相同。它会做同样的事情,但会创建一个索引。

在您的情况下:MySQL 将在使用唯一约束时在幕后使用唯一索引。所以在使用MySQL时,使用unique和使用unique index没有区别。

如果您使用其他数据库管理系统,则可能会有所不同。

差异(如果有的话)将由数据库管理系统内部处理。出于实际目的,您可以将它们视为相同。将记录每个数据库管理系统的差异。

关于go - unique_index 和 unique 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53611325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com