【问题标题】:select statement with dynamic columns for where condition带有用于 where 条件的动态列的 select 语句
【发布时间】:2020-11-19 19:52:20
【问题描述】:

我正在创建一个以 postgresql 作为后端的 nodejs 项目,我使用 pg_promise 作为查询驱动程序

目前我必须对可能不同但都具有相同相等条件检查的列执行选择语句,如下所示

    pg.any('select * from table where col1 = ${col1} and col2 = ${col2}',{
col1:value1,
col2:value2
});

// which generates the query shown below
// select * from table where col2 = value1 and col2 = value2;


我想要的是希望找到一种更简单的方法来生成选择查询,其中变量 no 的列具有相等的 where 条件,类似于 pg_promise 允许我们使用 helpers.update 来生成更新查询。

// something like shown below
pg.helpers.select('select * from table ',{col1:value1, col2:value2})
// it shoud generate the same as the query with static columns
//select * from table where col2 = value1 and col2 = value2;

【问题讨论】:

  • 您应该在问题中包含$(dynamic columns list) 的预期输出。否则,不清楚你想要什么。此外,适当地格式化您的问题会很好,也许是一个更好的标题。看起来一团糟。

标签: pg-promise


【解决方案1】:

pg-promise 不包含类似的内容,因为您正在寻找的是自定义的,而不是特别通用的解决方案,因为它可能需要AND/OR 逻辑、类型转换、使用嵌套属性等。

但是,该库确实为您提供了为自己创建此类自定义解决方案所需的所有工具。例如,如果您需要的只是对象中所有属性的AND 条件,您可以使用如下内容:

const andProps = obj => ({
    rawType: true,
    toPostgres: () => Object.keys(obj).map(k => {
        const val = obj[k];
        if (val === null || val === undefined) {
            return pgp.as.format('$1:name IS NULL', [k]);
        }
        return pgp.as.format('$1:name = $2', [k, val]);
    }).join(' AND ')
});

以上代码使用Custom Type Formatting,加上内部format函数。并为null/undefined增加了特殊条款,产生IS NULL。我在这里使用了:name 过滤器,但您也可以使用:alias 来获得更短的名称(请参阅SQL Names)。

使用示例

const obj = {
    id: null,
    name: 'John',
    age: 30
};

const data = await db.any('SELECT * FROM users WHERE $1', [andProps(obj)]);
//=> SELECT * FROM users WHERE "id" IS NULL AND "name" = 'John' AND "age" = 30

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2023-03-15
    • 2014-07-29
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    相关资源
    最近更新 更多