我正在尝试运行查询,以便它将重复插入或更新。我为重复项使用了唯一索引,但似乎无法正常工作。它仍然添加新记录。希望能有新的观点指出我的问题。谢谢。
这是我的图式
CREATE TABLE IF NOT EXISTS `pricing_puchasing` (
`custno` varchar(6) DEFAULT NULL COMMENT 'customer code',
`recipe` varchar(15) DEFAULT NULL,
`item` varchar(120) NOT NULL COMMENT 'Item Code from dProduce',
`unit_weight` double(12,4) DEFAULT NULL,
`case_cost` double(12,4) DEFAULT NULL COMMENT 'Projected cost of item',
`cost_per_lb` double(12,4) NOT NULL,
`projected_price` float(12,3) DEFAULT NULL COMMENT 'projected Price',
`projected_margin` float(12,3) DEFAULT NULL COMMENT 'Projected Margin',
`trend` tinyint(1) DEFAULT NULL COMMENT 'Trend status 1=up, 0=down',
`note` varchar(255) DEFAULT NULL COMMENT 'Note about the data',
`week_of` date NOT NULL COMMENT 'Week of this data',
`approved` tinyint(1) DEFAULT NULL COMMENT 'approval flag',
`last_edited_from` varchar(20) NOT NULL COMMENT 'identifier to know where it was last saved from',
`saved_at` datetime NOT NULL COMMENT 'Date time of save/update',
`saved_by` int(11) NOT NULL COMMENT 'Created by user ID'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Stores pricing purchasing data';
ALTER TABLE `pricing_puchasing`
ADD UNIQUE KEY `custno_recipe_item_week_of` (`custno`,`recipe`,`item`,`week_of`), ADD KEY `custno` (`custno`);
这是我正在测试的查询:
INSERT INTO pricing_puchasing
(recipe,item,unit_weight,case_cost,cost_per_lb,trend,note,week_of,saved_at,saved_by,approved,last_edited_from)
VALUES
('APPLEGRRAW','APPLEGRRAW',40.00,100.01,2.50,0,'','2014-07-28',NOW(),1,NULL,'purchasing')
ON DUPLICATE KEY UPDATE
unit_weight=40.00,case_cost=100.01,cost_per_lb=2.50,trend=0,note='',saved_at=NOW(),saved_by=1,approved=NULL,last_edited_from='purchasing'
编辑我解决了custno丢失的问题,但是我仍然对插入重复项有疑问。我创建了一个sqlfiddle。这次我正在测试2个NULL值,但还是不行...是我的架构还是我的查询问题?
一NULL
值不认为是“独一无二的”。唯一索引的第一列是custno
,您未在INSERT中提供该列的值,因此默认值NULL用作该列的值。
由于NULL值不被认为是唯一的,因此INSERT将不会引发重复的键异常。
尝试使用custno列的非NULL值。
另外,您可以VALUES()
在语句的UPDATE部分中使用特殊功能,以引用INSERT中提供的值。
ON DUPLICATE KEY UPDATE
unit_weight=VALUES(unit_weight),case_cost=VALUES(case_cost)
http://dev.mysql.com/doc/refman/5.5/zh-CN/miscellaneous-functions.html#function_values
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句