vij*_*jay 2 sql postgresql where-clause node.js
运行查询:
select * from employee where name = $1 and age = $2 and salary = $3;
问题查询:
select * from employee where name = $1 and age = $2;
我怎样才能写出一个
/* If $3 is PASSED Then ( and salary = $3) */
注:/ *我不能检查为空或空为$ 3不过去了那么$ 3将不能用于检查* /
在节点中我像这样使用
postGresAdaptor.executeQueryWithParameters(QUERY, QUERYPARAMS, function(error, result) {
if (error) {
callback(error);
} else {
data = result.data;
}
});
Run Code Online (Sandbox Code Playgroud)
不想在节点代码中添加逻辑,因为途中会有很多查询。
不是很清楚你的意思是 pass,但也许你的意思是这$3是一个可选参数,$3没有意义:不在乎?
SELECT *
FROM employee
WHERE name = $1
AND age = $2
AND ( $3 IS NULL OR salary = $3)
;
Run Code Online (Sandbox Code Playgroud)
一些数据:
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 )
;
Run Code Online (Sandbox Code Playgroud)
与准备好的查询相同:
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);
Run Code Online (Sandbox Code Playgroud)
输出:
CREATE TABLE
INSERT 0 4
PREPARE
name | age | salary
-------+-----+--------
Alice | 13 | 3
(1 row)
name | age | salary
-------+-----+--------
Alice | 13 | 3
(1 row)
Run Code Online (Sandbox Code Playgroud)