MySQL的独特索引由多个字段组成

时间:2011-01-17 22:19:27

标签: mysql unique-constraint unique-index

我们的数据库中有一种特殊的表格,用于存储其变化的历史记录。所谓的“自存档”表:

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'的记录,并使用这些创建唯一索引2个字段:* subscriber_id,current *。

问题是:如何在MySQL中完成这项工作?

1 个答案:

答案 0 :(得分:2)

您可以使用NULL值执行此操作。如果您使用NULL代替“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.

现在,这有点作弊,这意味着你无法完全按照自己的意愿获得数据。所以这个解决方案可能不适合您的需求。但是如果你可以以这种方式重写你的数据,它应该可以工作。

相关问题