2015-11-20 70 views
1

付款发生时,有时会在表格中捕获它的双重条目。 我想忽略复式捕获,所以我想插入记录时这些createduser_idamount领域应该是唯一的。 我如何制作它?下面是我的桌子。多个列的mysql唯一

CREATE TABLE `transactions` (
`id` int(20) NOT NULL AUTO_INCREMENT, 
`created` datetime NOT NULL, 
`modified` datetime NOT NULL, 
`user_id` int(20) NOT NULL, 
`project_id` int(20) DEFAULT NULL, 
`foreign_id` int(20) NOT NULL, 
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL, 
`transaction_type_id` int(20) DEFAULT NULL, 
`amount` float(10,2) NOT NULL, 
`description` text COLLATE utf8_unicode_ci, 
`payment_gateway_id` int(20) DEFAULT NULL, 
`gateway_fees` float(10,2) NOT NULL, 
`is_old` tinyint(1) NOT NULL DEFAULT '0', 
PRIMARY KEY (`id`) 
) ENGINE=MyISAM AUTO_INCREMENT=266 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci 
+0

你可以用'群创建者,USER_ID,amount' – madforstrength

+0

考虑使用表约束。 –

+0

这种方式很可能不希望在这个表中使用浮点数据类型 – Strawberry

回答

3

要严格回答您的问题,请在这3列的组合上创建一个独特的复合键。这样,复合索引中的3个组合就不会存在两行。

CREATE TABLE `transactions2` (
`id` int(20) NOT NULL AUTO_INCREMENT, 
`created` datetime NOT NULL, 
`modified` datetime NOT NULL, 
`user_id` int(20) NOT NULL, 
`project_id` int(20) DEFAULT NULL, 
`foreign_id` int(20) NOT NULL, 
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL, 
`transaction_type_id` int(20) DEFAULT NULL, 
`amount` float(10,2) NOT NULL, 
`description` text COLLATE utf8_unicode_ci, 
`payment_gateway_id` int(20) DEFAULT NULL, 
`gateway_fees` float(10,2) NOT NULL, 
`is_old` tinyint(1) NOT NULL DEFAULT '0', 
PRIMARY KEY (`id`), 
unique key(created,user_id,amount) -- <------------------- right here 
); 

插入一些数据,以测试它:

insert transactions2 (created,modified,user_id,project_id,foreign_id,class, 
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values 
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1); 

- 插入细(上文)

具有完全相同的数据再次尝试:

insert transactions2 (created,modified,user_id,project_id,foreign_id,class, 
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values 
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1); 

- 错误1062:重复录入

- 几乎没有改变:

insert transactions2 (created,modified,user_id,project_id,foreign_id,class, 
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values 
('2009-01-01 13:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1); 

- 插入精细

此外,使用​​。阅读关于Here

请仔细阅读Mysql multi column indexes又称为复合索引。

最后,你说的是什么的概念并非遥不可及Insert on Duplicate Key Update。只要把这个参考文献给你。

+0

嗯,金额通常不会形成一个PK的组成部分 – Strawberry

+0

只需严格回答,@Strawberry。我同意。它是不是一个PK – Drew

+0

节省打字 – Strawberry

0

可以使用达到同样的,在插入时的处理,

你可以尝试用WHERE NOT EXISTSINSERT

这样的事情。(你需要指定谁已经NOT NULL约束,我错过了所有这些列列名)

INSERT INTO table_name(`created`,`user_id`,`amount`) VALUES = 
    '$created','$user_id','$amount' 
    WHERE NOT EXISTS 
    (SELECT * 
     FROM table_name 
      WHERE created ='$created' AND user_id='$user_id' AND amount='$amount') 

希望这有助于。

+0

语法错误。另外他还有'你不理睬的'空'列。你再次编造语法兄弟:) – Drew