MySQL 多个字段的唯一索引
我们的数据库中有一种特殊的表,它本身存储其更改的历史记录。所谓的“自存档”表:
CREAT TABLE coverages (
id INT, # primary key, auto-increment
subscriber_id INT,
current CHAR, # - could be "C" or "H".
record_version INT,
# etc.
);
它存储我们订阅者的“覆盖范围”。字段“当前”指示这是当前/原始记录(“C”)还是历史记录(“H”)。
对于给定订阅者,我们只能有一个当前的“C”覆盖范围,但我们无法创建具有 2 个字段(*subscriber_id 和 current*)的唯一索引,因为对于任何给定的“C”记录,可能有任意数量的“H” “记录——变化的历史。
因此,索引仅对于 current == 'C' 和任何subscriber_id 来说应该是唯一的。
这可以在 Oracle DB 中使用“物化视图”之类的东西来完成:我们可以创建一个物化视图,该视图仅包含 current = 'C' 的记录,并使用这两个字段创建一个唯一索引: *订阅者 ID,当前*。
问题是:如何在 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
NULL
值来执行此操作。如果使用NULL
而不是“H
”,MySQL 在评估UNIQUE
约束时会忽略该行:现在,这有点作弊,这意味着你无法拥有你的数据完全如您所愿。所以这个解决方案可能不适合您的需求。但是,如果您可以以这种方式重新处理数据,那么它应该可以工作。
You can do this using
NULL
values. If you useNULL
instead of "H
", MySQL will ignore the row when evaluating theUNIQUE
constraint: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.