简体   繁体   English

具有条件MYSQL的唯一约束

[英]Unique constrain with condition MYSQL

I have User table in my DB. 我的数据库中有用户表。

A user has the fields name, company_id and status: boolean, 1- live, 0- deleted. 用户具有字段名称,company_id和status:boolean,1- live,0- deleted。

When a user is deleted, his status is set to 0. 删除用户后,其状态将设置为0。

The combination of a live user name in a company should be unique. 公司中的实时用户名组合应该是唯一的。 After a user is deleted, I don't mind that a user should be created with the same name for the company. 删除用户后,我不介意应该为公司创建具有相同名称的用户。

My question is how do I define a uniuqe constrain for the fields name, company_id and status=1 (It's not a uniuqe constrain on those three field becuase I don't mind that the combination of name-company_id-0 will appear a few times in the table). 我的问题是如何为字段名称,company_id和status = 1定义uniuqe约束(这不是对这三个字段的限制因为我不介意name-company_id-0的组合会出现几次在表中)。

Thanks, 谢谢,

Dvora 德沃拉

Use NULL value for deleted users. 对已删除的用户使用NULL值。
Unique key allows unlimited number of NULL values. 唯一键允许无限数量的NULL值。

Update: Don't touch user name, NULL in status field is enough. 更新:不要触摸用户名,状态字段中的NULL就足够了。

Which programming language you are using? 您使用的是哪种编程语言?

your logic shoule be as follows 你的逻辑应该如下

select * from Table_name where name='' AND company_id = '' AND status = 1

if this return any rows give uniqueness error to the user else create it.

I would create another column to store a deleted user's previous name and set their real name to NULL when they're deleted (as well as setting the status to 0). 我将创建另一列来存储已删除用户的先前名称,并在删除它们时将其真实名称设置为NULL(以及将状态设置为0)。

Then have a unique constraint on name and company. 然后对名称和公司有一个独特的约束。 NULLs will not affect the uniqueness (since NULL != NULL ) and you can still recover the user's original name if desired. NULL不会影响唯一性(因为NULL != NULL ),如果需要,您仍然可以恢复用户的原始名称。

So the delete operation is something like: 所以删除操作类似于:

update users
    set prev_name = name,
        name = null,
        status = 0
where name = 'paxdiablo' and company = 'SmallGreen';

如果你拆分“实时”和“删除”这样它们有自己的tinyint / boolean列会更容易吗?

I would replace status field with deleted_at (datetime). 我会用deleted_at(datetime)替换status字段。 When the user is active its value would be NULL, but when deleted, it would be set to current datetime. 当用户处于活动状态时,其值将为NULL,但在删除时,它将设置为当前日期时间。

Next, i would add unique index on username & deleted_at fields, which will allow me to delete more than one user with the same username (in at least 1 second interval). 接下来,我将在username和deleted_at字段上添加唯一索引,这将允许我删除具有相同用户名的多个用户(至少1秒间隔)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM