运行查询:
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
) */
注意: /* 我无法检查 null 或 Empty 作为 $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/