2015-11-20 76 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