我试图插入新行或更新现有的行(如果已经包含它)。
我想我可以用索引来试试但是老实说我不知道怎么做这个因此我试着用IF语句来做。 不幸的是,这不起作用,因为它说我的语法有问题。我正在使用MariaDB。
IF NOT EXISTS (SELECT * FROM valuation
WHERE ticker = 'BK001EUR' AND depot_id =1
AND src_id =2 AND valuation_date ='2009-09-09')
INSERT INTO valuation (ticker,depot_id,src_id,valuation_date,value)
VALUES ('BK001EUR',1,2,'2009-09-09',14999260.46)
ELSE
UPDATE valuation
SET value =14999260.46
WHERE ticker = 'BK001EUR' AND depot_id =1
AND src_id =2 AND valuation_date ='2009-09-09');
答案 0 :(得分:1)
您可以使用:
-- if exists then it will update
UPDATE valuation
SET value =14999260.46
WHERE ticker = 'BK001EUR'
AND depot_id =1 AND src_id =2 AND valuation_date ='2009-09-09';
-- if not exist then insert
INSERT INTO valuation (ticker,depot_id,src_id,valuation_date,value)
SELECT 'BK001EUR',1,2,'2009-09-09',14999260.46
WHERE NOT EXISTS (SELECT 1
FROM valuation
WHERE ticker = 'BK001EUR'
AND depot_id =1
AND src_id =2 AND valuation_date ='2009-09-09');
或更好的方式INSERT ON DUPLICATE UPDATE
:
INSERT INTO valuation (ticker,depot_id,src_id,valuation_date,value)
VALUES ('BK001EUR',1,2,'2009-09-09',14999260.46)
ON DUPLICATE KEY UPDATE value =14999260.46;
答案 1 :(得分:1)
执行此操作的正确方法是使用insert ... on duplicate key update
。我会把查询写成:
INSERT INTO valuation (ticker, depot_id, src_id, valuation_date, value)
VALUES ('BK001EUR', 1, 2, '2009-09-09', 14999260.46)
ON DUPLICATE KEY UPDATE value = VALUES(value);
(请注意使用VALUES()
,这样您就不必重复输入。)
要使其正常工作,您需要在您关注的密钥上使用唯一索引:
create unique index unq_valuation_4 on valuation(ticker, depot_id, src_id, valuation_date);
重复键不需要是主键索引 它可以是任何唯一索引。
6个字符