pg-promise 快速删除元组集的方法

pg-promise quick way to delete set of tuples

有没有更好的写法:

DELETE FROM
    table
WHERE
    _id = $<id>
    AND (
        item_id = $<item_id>
        AND map_id = $<map_id>
        OR
        item_id = $<another_id>
        AND map_id = $<another_map_id>
        ...
    )

我的数据集格式是:

[
    {
        item_id: "some_id",
        map_id: "other_id"
    }
    ...
]

pg-promise 或什至只是普通的 postgreSQL 写这个的好方法是什么?

Postgres 支持元组相等,所以你可以这样写:

DELETE FROM table
WHERE
    _id = $<id>
    AND (item_id, map_id) IN ( 
        ($<item_id>, $<map_id>),
        ($<another_id>, $<another_map_id>),
        ...
    )
DELETE FROM table
WHERE
    _id = $<id>
    AND (item_id, map_id) IN ($<values:raw>)

如果您将以下内容作为输入数据:

const input = [
    {
        item_id: 'some_id',
        map_id: 'other_id'
    }
    ...
];

然后你可以生成 valuespg-promise as follows (see helpers.values):

const values = pgp.helpers.values(input, ['item_id', 'map_id']);

或者如果需要更多详细信息,例如类型转换等,您可以将列作为完整的 ColumnSet 传递。