0

我必须用列构建一个表

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

现在我需要将值插入到这个表中,这样插入到 col3 中的值不会重复 col2 中的一组值......需要实现的约束是什么?......

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

列中的值Keywords可以重复 - 但对于 中的某些值ID_CategoryKeywords值不需要重复。你能帮我如何实现这个吗?

4

1 回答 1

1

使用来自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 ;
于 2011-04-08T09:45:56.567 回答