如何在表中实现约束,使插入的值仅对一组行重复


how to implement constraint in table such that inserted values do not repeat for group of rows only

我必须构造一个包含列的表

col1(主键)col2(不空)col3(不空)col4(不空)

现在我需要将值插入到这个表中,这样插入到col3中的值不会重复到col2....中的值集

需要实现哪些约束??

值可以在col3中作为一个整体重复…但是对于一些col2的值,col3中的值不需要重复。这是列名。
ID ID_Category Keywords Score

Keywords列中的值可以重复,但对于ID_Category中的某些值,Keywords的值不必重复。你能帮我怎么实现这个吗??

使用http://forge.mysql.com/wiki/Triggers#Emulating_Check_Constraints

中的代码

首先创建这个通用错误表

CREATE TABLE `Error` (                                                                                                         
      `ErrorGID` int(10) unsigned NOT NULL auto_increment,                                                                         
      `Message` varchar(128) default NULL,                                                                                         
      `Created` timestamp NOT NULL default CURRENT_TIMESTAMP 
      on update CURRENT_TIMESTAMP,                                          
      PRIMARY KEY (`ErrorGID`),                                                                                                   
      UNIQUE KEY `MessageIndex` (`Message`))
      ENGINE=MEMORY 
      DEFAULT CHARSET=latin1 
      ROW_FORMAT=FIXED 
      COMMENT='The Fail() procedure writes to this table twice to force a constraint failure.';

创建失败的泛型函数

DELIMITER $$
DROP PROCEDURE IF EXISTS `Fail`$$
CREATE PROCEDURE `Fail`(_Message VARCHAR(128))
BEGIN
  INSERT INTO Error (Message) VALUES (_Message);
  INSERT INTO Error (Message) VALUES (_Message);
END$$
DELIMITER ;

现在您可以在任何表上创建自定义约束了,比如您的

DELIMITER $$
create trigger mytable_check before insert on test.mytable for each row
begin
 if new.id_category in ('list','of','special','categories')
    and exists
      (select * from mytable
       where id_category=new.id_category
         and keywords=new.keywords) then
    call fail(concat('id_category,keywords must be unique when id_category is: ',new.id_category));
 end if;
end $$
DELIMITER ;