我有以下查询,我使用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;
我很想听听有关如何简化此查询的想法。
答案 0 :(得分:3)
只要做你正在做的事情,没有循环:
project
当然,您可以在knowledge_state(lo_id,learner_id)上添加索引以使其更快(On Conflict意味着唯一约束或其他约束,而唯一约束意味着索引)。