我正在尝试编写一个查询,以防止插入重复的行,如下所示
INSERT INTO RSS_SETTING_ADMIN (ID_PRODUCT , ID_RSS , ID_CATEGORY , ID_TYPE_USER)
VALUES (384 , 3, 283 , 1)WHERE NOT EXISTS
(SELECT * FROM RSS_SETTING_ADMIN
WHERE ID_PRODUCT = 384 , ID_RSS = 3 , ID_CATEGORY = 283, ID_TYPE_USER = 1)
但我收到了
SQL命令未正确结束
错误
答案 0 :(得分:1)
你的命令应该是:
INSERT INTO RSS_SETTING_ADMIN (ID_PRODUCT , ID_RSS , ID_CATEGORY , ID_TYPE_USER)
SELECT 384 , 3, 283 , 1 FROM DUAL
WHERE NOT EXISTS
(SELECT * FROM RSS_SETTING_ADMIN
WHERE ID_PRODUCT = 384
AND ID_RSS = 3
AND ID_CATEGORY = 283
AND ID_TYPE_USER = 1
);
我还记得你不足以防止重复的行,你需要一个唯一的密钥。
答案 1 :(得分:0)
您应该将查询更改为此
INSERT INTO RSS_SETTING_ADMIN (ID_PRODUCT , ID_RSS , ID_CATEGORY , ID_TYPE_USER)
select 384 , 3, 283 , 1
from dual
WHERE NOT EXISTS (SELECT *
FROM RSS_SETTING_ADMIN
WHERE ID_PRODUCT = 384 and ID_RSS = 3
and ID_CATEGORY = 283 and ID_TYPE_USER = 1
);
答案 2 :(得分:0)
如果要阻止插入重复值,则应在表上使用唯一约束/索引:
alter table RSS_SETTING_ADMIN
add constraint unq_RSS_SETTING_ADMIN_4 unique(id_product, id_rss, id_category, id_type_user);
让数据库维护关系完整性而不是应用程序是一种更好的方法。
如果您仍想使用not exists
,我建议:
insert intoRSS_SETTING_ADMIN (ID_PRODUCT , ID_RSS , ID_CATEGORY , ID_TYPE_USER)
select x.id_product, x.id_rss, x.id_category, x.id_type_user
from (select 384 as id_product, 3 as id_rss, 283 as id_category, 1 as id_type_user
from dual
) x
where not exists (select 1
from RSS_SETTING_ADMIN rsa
where rsa.id_product = x.id_product and
rsa.id_rss = x.id_rss and
rsa.id_category = x.id_category and
rsa.id_type_user = x.id_type_user
);
使用此结构,值只包含在查询中一次,这样可以更容易避免拼写错误。