Postgresql:如何使以下查询更有效

时间:2010-09-02 04:23:44

标签: sql postgresql

我有一个程序,我必须检查某个指定条目的某个视图并相应地删除它们。我为此目的使用了以下方法 -

SELECT      id_1,
            id_2, 
            id_3, 
            id_4
INTO        v_id_1,
            v_id_2, 
            v_id_3,
            v_id_4
FROM        v_doc
WHERE       parent_id_1 = p_id_1    -- 'p_' suffix stands for function parameters
            AND parent_id_2 = p_id_2
            AND parent_id_3 = p_id_3
LIMIT       1
;

WHILE v_id_1 IS NOT NULL
LOOP
    -- Code for child document line deletion goes here


    SELECT      id_1,
                id_2, 
                id_3, 
                id_4
    INTO        v_id_1,
                v_id_2, 
                v_id_3,
                v_id_4
    FROM        v_doc
    WHERE       parent_id_1 = p_id_1
                AND parent_id_2 = p_id_2
                AND parent_id_3 = p_id_3
    LIMIT       1
    ;
END LOOP;

这是有效的方式,还是有更有效的方法来执行此类查询?我当然是在谈论我选择记录的方式。

2 个答案:

答案 0 :(得分:3)

如果您的查询返回多行,我想您想知道如何删除每个匹配的项目。更快更正确的方法是运行查询一次,并循环遍历其行:

DECLARE
    r RECORD;
BEGIN
    FOR r IN SELECT id_1, id_2, id_3, id_4 
               FROM v_doc 
              WHERE id_1 = p_id_1 
                AND id_2 = p_id_2 
                AND id_3 = p_id_3 LOOP
        -- delete item for r.id_1, r.id_2, etc.
    END LOOP;
END;

请参阅http://www.postgresql.org/docs/8.4/static/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING

如果可能的话,更好的方法可能是简单地使用DELETE FROM x WHERE ...语句。这取决于删除的简单程度。

答案 1 :(得分:2)

我怀念使用的东西:

DELETE FROM v_doc
 WHERE EXISTS(SELECT NULL
                FROM v_doc x
               WHERE x.id_1 = v_doc.id_1
                 AND x.id_2 = v_doc.id_2
                 AND x.id_3 = v_doc.id_3
                 AND x.id_4 = v_doc.id_4
                 AND x.parent_id_1 = p_id_1
                 AND x.parent_id_2 = p_id_2
                 AND x.parent_id_3 = p_id_3)