sql - 如果参数为 'where' postgresql,如何避免 'NOT PASSED' 子句中的列

标签 sql node.js postgresql where-clause

运行查询:

select * from employee where name = $1 and age = $2 and salary = $3;

问题查询:

select * from employee where name = $1 and age = $2;

我怎样才能写出这样的逻辑 /* 如果 $3 是 PASSED Then (and salary = $3 ) */

注意: /* 我无法检查 nullEmpty 作为 $3 因为没有通过然后 $3 将无法用于check*/

在 Node 中我是这样使用的

        postGresAdaptor.executeQueryWithParameters(QUERY, QUERYPARAMS, function(error, result) {
            if (error) {
                callback(error);
            } else {                    
                data = result.data;                    
            }
        });

不想在 Node 代码中添加逻辑,因为途中会有很多查询。

最佳答案

不是很清楚你所说的被传递是什么意思,但也许你的意思是$3是一个可选参数,$3不存在意思是:不在乎 ?

SELECT *
FROM employee
WHERE name = $1
AND age = $2
AND ( $3 IS NULL OR salary = $3)
   ;

一些数据:

CREATE TABLE employee
        ( name varchar NOT NULL PRIMARY KEY
        , age integer
        , salary integer
        );

INSERT INTO employee ( name , age , salary ) VALUES
 ( 'Alice' , 13 , 3 )
,( 'Bob' , 11 , 5 )
,( 'Charlotte' , 15 , 9 )
,( 'David' , 17 , 10 )
        ;

与准备好的查询相同:

PREPARE qry (text, integer , integer) AS
SELECT *
FROM employee
WHERE name = $1
AND age = $2
AND ( $3 IS NULL OR salary = $3)
   ;

    -- and call the prepared statement:
EXECUTE qry ('Alice', 13, 3);
EXECUTE qry ('Alice', 13, NULL);

输出:

CREATE TABLE
INSERT 0 4
PREPARE
 name  | age | salary 
-------+-----+--------
 Alice |  13 |      3
(1 row)

 name  | age | salary 
-------+-----+--------
 Alice |  13 |      3
(1 row)

关于sql - 如果参数为 'where' postgresql,如何避免 'NOT PASSED' 子句中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30048016/

相关文章:

sql - 将列表传递给 SQL 自定义类型

javascript - 使用 johnny-five 和 arduino 读取输入引脚

java - 如何将 Java 与 nodejs 集成以处理 CPU 繁重的任务?

javascript - 如何在 sequelize.js 中正确映射关系的属性?

java - Azure 使用 Azure Java SDK 在资源组中列出 Azure Database for PostgreSQL 服务器

python - 链中存在多个一对多映射的长链存在查询

sql - 有什么比 P6Spy 更好的吗?

php - 使用 codeigniter 的事件记录在 SQL 语句末尾放置 where 子句

mysql - 更新 : ERROR 1265 (01000): "Data truncated for column at row 1"

node.js - Amazon SES 与 Node 邮件程序