gpt4 book ai didi

mysql - 如何将字符串列的串联作为 MySQL 中的唯一约束

转载 作者:搜寻专家 更新时间:2023-10-30 20:23:42 25 4
gpt4 key购买 nike

我有一个表说 employee employee 表有几个字段,例如

`salary`
`name`
`age`
`designation`

其中只有designation 可以为空。我无法将其设为 NOT NULL,因为现有代码正在使用它。

是否可以为上述所有列创建组合唯一约束??

当我尝试创建新的唯一约束时。

ALTER TABLE `employee` ADD CONSTRAINT `employee_constraint` 
UNIQUE key (`salary`,`name`, `age`, `designation`);

它成功创建了约束,但是当我尝试插入这些记录的重复组合时,它插入成功。有没有更好的方法来创建约束并丢弃这些列的重复组合?

最佳答案

通常 MySQL 允许在 UNIQUE 约束中使用多个 NULL。更多信息:Does MySQL ignore null values on unique constraints?

您可以使用生成的列只允许一个 NULL 值:

CREATE TABLE employee(salary INT, name VARCHAR(100)
,age INT, designation VARCHAR(100)
,designation_virtual VARCHAR(100) AS (COALESCE(designation, '^'))
);

ALTER TABLE employee ADD CONSTRAINT employee_constraint
UNIQUE key (salary,name, age, designation_virtual) ;

INSERT INTO employee(salary, name, age, designation)
VALUES(1000, 'xyz', 10, NULL);

INSERT INTO employee(salary, name, age, designation)
VALUES(1000, 'xyz', 10, NULL);
-- Duplicate entry '1000-xyz-10-^' for key 'employee_constraint'

SELECT * FROM employee;

DBFiddle Demo


如果您使用的是 MariaDB 10.3.3,您可以将虚拟列标记为 INVISIBLE .

Columns can be given an INVISIBLE attribute. These columns will then not be listed in the results of a SELECT * statement, nor do they need to be assigned a value in an INSERT statement, unless INSERT explicitly mentions them by name.

ALTER TABLE employee MODIFY designation_virtual INVISIBLE;  

关于mysql - 如何将字符串列的串联作为 MySQL 中的唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50781892/

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