【问题标题】:how to implement constraint in table such that inserted values do not repeat for group of rows only如何在表中实现约束,以使插入的值不会仅对一组行重复
【发布时间】:2011-08-01 08:51:43
【问题描述】:

我必须构建一个带有列的表

col1(主键) col2(not null) col3(not null) col4(not null)

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

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

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

【问题讨论】:

  • 如果这不是您需要的,请更具体一些,显示您拥有的一些代码和您需要的结果。
  • 不需要重复是什么意思?
  • 对于 ID_Category 的某些值来说意味着唯一
  • 我现在清楚了吗??...我应该添加更多信息吗??

标签: php mysql mysql5


【解决方案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 ;

【讨论】:

  • 括号中的值是什么?--------------------new.id_category in ('list','of','special', '类别')
  • 你能解释一下这行吗?---- if new.id_category in ('list','of','special','categories')
  • 如果你想让(category,keyword)在category为A,B,C时唯一,那么你使用条件if new.id_category in ('A','B','C')等。如果category不在列表中,唯一性未选中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
相关资源
最近更新 更多