简体   繁体   English

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

[英]Postgresql: How to make the following query more efficient

I have a procedure, where I have to check a certain view for some specified entries and delete them accordingly. 我有一个过程,其中我必须检查某个视图中是否有某些指定的条目,并相应地删除它们。 I have used the following approach for this purpose - 为此,我使用了以下方法-

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;

Is this is the efficient way, or there is a more efficient way to do this type of query? 这是有效的方法,还是有一种更有效的方法来进行这种类型的查询? I am talking about the way I am selecting the records, of course. 当然,我在谈论我选择记录的方式。

I think you're wondering how you can delete each matching item, if your query returns many rows. 我想您想知道如果查询返回很多行,如何删除每个匹配项。 A quicker and correcter way is to run the query once, and loop over its rows: 一种更快且更正确的方法是运行一次查询,然后遍历其行:

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;

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

An even better way might be to simply use a DELETE FROM x WHERE ... statement, if possible. 如果可能的话,一个更好的方法可能是简单地使用DELETE FROM x WHERE ...语句。 It depends how simple the deletion is. 这取决于删除的简单程度。

Is there something I miss about using: 我有什么想念的吗?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM