我正在尝试使用这个单一语句更新多个记录(大约一千个)(这是一个每晚都会运行的进程)。以下声明仅包含3种简单产品:
INSERT INTO productinventory
(ProductID, VendorID, CustomerPrice, ProductOverrides)
VALUES
(123, 3, 100.00, 'CustomerPrice'),
(124, 3, 100.00, 'CustomerPrice'),
(125, 3, 100.00, 'CustomerPrice')
ON DUPLICATE KEY UPDATE
CustomerPrice = VALUES(CustomerPrice),
ProductOverrides = CONCAT_WS(',', ProductOverrides, 'CustomerPrice')
;
除了ProductOverrides
列每次运行此语句时都会向其添加文本'CustomerPrice'
以外,所有内容都可以正常工作,因此在运行两次之后它会看起来像这样:
CustomerPrice,CustomerPrice
我希望声明要做的是将'CustomerPrice'
添加到ProductOverrides
列,但仅当那个字符串不存在时才会添加。因此,无论我运行此语句多少次,它只包含该字符串一次。如何修改此语句以实现此目的?
答案 0 :(得分:0)
你可以做这样的事情
INSERT INTO productinventory (ProductID, VendorID, CustomerPrice, ProductOverrides)
VALUES
(123, 3, 100.00, 'CustomerPrice'),
(124, 3, 100.00, 'CustomerPrice'),
(125, 3, 100.00, 'CustomerPrice')
ON DUPLICATE KEY UPDATE
CustomerPrice = VALUES(CustomerPrice),
ProductOverrides = IF(FIND_IN_SET(VALUES(ProductOverrides), ProductOverrides) > 0,
ProductOverrides,
CONCAT_WS(',', ProductOverrides, VALUES(ProductOverrides)));
这是 SQLFiddle 演示