我有以下查询,我使用postgres 9.5:
INSERT INTO knowledge_state
(SELECT learnerid learner_id, lo_id FROM qb_lo_tag WHERE qb_id = NEW.qb_id)
ON CONFLICT DO NOTHING ;
不幸的是我不能在某些服务器上使用postgres 9.5,我需要将它转换为9.5之前的友好查询.
我已经构建了以下查询,但对我来说似乎要复杂得多,我认为可能更简单.
FOR rows IN SELECT lo_id FROM knowledge_state
WHERE learner_id = learnerid
AND lo_id IN (SELECT lo_id FROM qb_lo_tags WHERE qb_id = New.qb_id) LOOP
INSERT INTO knowledge_state (lo_id, learner_id) SELECT rows.lo_id, learnerid
WHERE NOT EXISTS (SELECT * FROM knowledge_state WHERE lo_id = rows.lo_id AND learner_id = learnerid);
END LOOP;
我很想听听如何简化此查询的想法.
最佳答案 只是做你正在做的事情,没有循环:
INSERT INTO knowledge_state (lo_id, learner_id)
SELECT a.lo_id, a.learnerid
FROM qb_lo_tag a
WHERE a.qb_id = NEW.qb_id
and NOT EXISTS (SELECT * FROM knowledge_state b
WHERE b.lo_id = a.lo_id AND b.learner_id = a.learnerid);
当然,您可以在knowledge_state(lo_id,learner_id)上添加索引以使其更快(On Conflict意味着唯一约束或其他约束,而唯一约束意味着索引).