2

假设一个表有 3 列,那么我可以制作它,以便当(且仅当)第 3 列等于 x 时,第 1 列和第 2 列之间的混合是唯一的?

这将使这项工作:

-------------------------------------------------- ---
| 一个 | 乙| C |
-------------------------------------------------- ---
| 1 | 2 | x |
-------------------------------------------------- ---
| 2 | 1 | x |
-------------------------------------------------- ---
| 0 | 0 | 是 |
-------------------------------------------------- ---
| 0 | 0 | 是 |
-------------------------------------------------- ---

这不会:

| 一个 | 乙| C |
-------------------------------------------------- ---
| 2 | 2 | x |
-------------------------------------------------- ---
| 2 | 2 | x |
-------------------------------------------------- ---
| 0 | 0 | 是 |
-------------------------------------------------- ---
| 0 | 0 | 是 |
-------------------------------------------------- ---
4

2 回答 2

2

您可以创建触发器:

DELIMITER ;;

CREATE TRIGGER special_unique_test BEFORE INSERT ON my_table FOR EACH ROW
IF NEW.C = 'x' AND EXISTS (
  SELECT * FROM my_table WHERE A = NEW.A AND B = NEW.B AND C = 'x'
) THEN
  CALL raise_error;
END IF;;

DELIMITER ;

我建议维护一个索引(A, B, C)以保持合理的性能。

INSERT ... ON DUPLICATE KEY UPDATE但是,这不会产生与REPLACE真正UNIQUE密钥相同的好处。

于 2012-10-14T10:21:53.813 回答
0

尝试:

select distinct a, b, c
from mytable
where c = 'x'
union all
select a, b, c
from mytable
where c <> 'x'
于 2012-10-14T10:15:52.417 回答