mysql 多列唯一索引,MySQL唯一索引由多个字段

We have a special kind of table in our DB that stores the history of its changes in itself. So called "self-archived" table:

CREAT TABLE coverages (

id INT, # primary key, auto-increment

subscriber_id INT,

current CHAR, # - could be "C" or "H".

record_version INT,

# etc.

);

It stores "coverages" of our subscribers. Field "current" indicates if this is a current/original record ("C") or history record ("H").

We could only have one current "C" coverage for the given subscriber, but we can't create a unique index with 2 fields (*subscriber_id and current*) because for any given "C" record there could be any number of "H" records - history of changes.

So the index should only be unique for current == 'C' and any subscriber_id.

That could be done in Oracle DB using something like "materialized views": where we could create a materialized view that would only include records with current = 'C' and create a unique index with these 2 fields: *subscriber_id, current*.

The question is: how can this be done in MySQL?

解决方案

You can do this using NULL values. If you use NULL instead of "H", MySQL will ignore the row when evaluating the UNIQUE constraint:

A UNIQUE index creates a constraint such that all values in the index must be

distinct. An error occurs if you try to add a new row with a key value that

matches an existing row. This constraint does not apply to NULL values except

for the BDB storage engine. For other engines, a UNIQUE index permits multiple

NULL values for columns that can contain NULL.

Now, this is cheating a bit, and it means that you can't have your data exactly as you want it. So this solution may not fit your needs. But if you can rework your data in this way, it should work.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值