gpt4 book ai didi

mysql - 多列主键中的 NULL 值

转载 作者:IT老高 更新时间:2023-10-28 12:55:59 26 4
gpt4 key购买 nike

我有一个表,其中有几列构成主键。所存储数据的性质允许其中一些字段具有 NULL 值。我的 table 是这样设计的:

CREATE TABLE `test` (
`Field1` SMALLINT(5) UNSIGNED NOT NULL,
`Field2` DECIMAL(5,2) UNSIGNED NULL DEFAULT NULL,
PRIMARY KEY (`Field1`, `Field2`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;

但是,当我运行 describe test 时,它显示如下:

|| *Field* || *Type*                || *Null* || *Key* || *Default* || *Extra* 
|| Field1 || smallint(5) unsigned || NO || PRI || ||
|| Field2 || decimal(5,2) unsigned || NO || PRI || 0.00 ||

插入 NULL 值时,我不断收到错误消息。

Column 'Field2' cannot be null

这是因为作为主键一部分的字段不能为空吗?除了对 NULL 使用 '0' 之外,我还有什么替代方法?

最佳答案

来自 MySQL 文档:

PRIMARY KEY

A unique index where all key columns must be defined as NOT NULL. Ifthey are not explicitly declared as NOT NULL, MySQL declares them soimplicitly (and silently). A table can have only one PRIMARY KEY. Thename of a PRIMARY KEY is always PRIMARY, which thus cannot be used asthe name for any other kind of index.

https://dev.mysql.com/doc/refman/8.0/en/create-table.html

如果 Field2 可以为 NULL,我质疑您为什么需要它作为主键的一部分,因为您需要 Field1 在所有行中都是不同的。所以 Field1 本身应该足以作为主键。您可以在 Field2 上创建不同类型的索引。

关于mysql - 多列主键中的 NULL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11001333/

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