我想插入一个新数据,但我想在查询中放入一个条件,如果有数据存在,则不会插入,如果不存在则可以插入。
INSERT INTO user_permission_index (guid, code, name,description, perm_type, time_create)
VALUES
(uuid_generate_v1(),'perm_trading_cashsale_by_branch','label_CanissueCashsaleByBranch','','acc_branch_index','0001-01-01')
WHERE NOT EXISTS (SELECT *
FROM user_permission_index
WHERE code = 'perm_trading_cashsale_by_branch'
AND name = 'label_CanissueCashsaleByBranch');
我在WHERE NOT时遇到语法错误。你们能帮助我吗?感谢。
答案 0 :(得分:2)
您需要使用SELECT
代替VALUES
INSERT INTO user_permission_index (guid, code, name,description, perm_type, time_create)
select uuid_generate_v1(),
'perm_trading_cashsale_by_branch',
'label_CanissueCashsaleByBranch',
'',
'acc_branch_index',
'0001-01-01'
WHERE NOT EXISTS (SELECT *
FROM user_permission_index
WHERE code = 'perm_trading_cashsale_by_branch'
AND name = 'label_CanissueCashsaleByBranch');
(我假设你是PostgreSQL,因为uuid_generate_v1()
函数)
如果您正在使用“更新或插入”功能,可能需要查看以下内容:Insert, on duplicate update in PostgreSQL?
答案 1 :(得分:0)
您需要将内部选择链接到外部插入语句
INSERT INTO user_permission_index upi (guid, code, name,description, perm_type, time_create)
SELECT (uuid_generate_v1(),'perm_trading_cashsale_by_branch','label_CanissueCashsaleByBranch','','acc_branch_index','0001-01-01')
WHERE NOT EXISTS (
SELECT *
FROM user_permission_index
WHERE code = 'perm_trading_cashsale_by_branch'
AND name = 'label_CanissueCashsaleByBranch'
AND id = upi.id
);
但我认为说
会更好INSERT INTO user_permission_index (guid, code, name,description, perm_type, time_create)
SELECT (uuid_generate_v1(),'perm_trading_cashsale_by_branch','label_CanissueCashsaleByBranch','','acc_branch_index','0001-01-01')
WHERE nvl(code, '') <> 'perm_trading_cashsale_by_branch'
OR nvl(name, '') <> 'label_CanissueCashsaleByBranch';