我正在尝试在CTE返回 null false时插入一行,但是我不知道该怎么做
不工作:
with cte as (SELECT EXISTS (SELECT * FROM commentsvoted WHERE id = $1 AND user_id = $2))
INSERT INTO commentsvoted =
(CASE WHEN cte.exists IS FALSE (id, user_id, votes, thread_id) VALUES($1,
$2, true, $3)
ELSE commentsvoted
END)
我的cte:
with cte as (SELECT EXISTS (SELECT * FROM commentsvoted WHERE id = $1 AND user_id = $2))
当大小写为 null false时我想插入的内容:
INSERT INTO commentsvoted(id, user_id, votes, thread_id) VALUES($1, $2, true, $3)
答案 0 :(得分:0)
我想这就是你想要的:
WITH cte as (
SELECT EXISTS (SELECT * FROM commentsvoted WHERE id = $1 AND user_id = $2) as flag
)
INSERT INTO commentsvoted (id, user_id, votes, thread_id)
SELECT $1, $2, true, $3
FROM cte
WHERE NOT FLAG;
CTE将不包含NULL
,因为EXISTS
返回true或false。
我的意思是,这就是您想要的。您可能只希望在表上具有唯一索引:
create unique index unq_commentsvoted_id_user_id on commentsvoted(id, user_id);
然后数据库将阻止您插入重复的值。