【发布时间】:2020-01-08 12:25:30
【问题描述】:
我有一个存储在 SQL 文件中的复杂查询,我想将它重用于各种路由,但根据路由更改 WHERE 子句。这将代替在多个文件中进行大型复杂查询,唯一的区别是 WHERE 语句。
是否可以在使用 QueryFile 时动态添加 WHERE?简化示例如下:
SELECT "id", "userId", "locationId", "title", "body",
(
SELECT row_to_json(sqUser)
FROM (
SELECT "id", "firstname", "lastname"
FROM "users"
WHERE "users"."id" = "todos"."userId"
) sqUser
) as "user"
FROM "todos"
const queryIndex = new pgp.QueryFile('sql/todos/index.pgsql', queryOptions);
// 1. Use as is to get a list of all todos
// 2. OR Append WHERE "locationId" = $1 to get list filtered by location
// 3. OR Append WHERE "id" = $1 to get a specific item
// without having three separate SQL files?
看起来(也许?)您可以在查询文件中添加以下内容,但这仍然感觉有限(仍然需要两个文件用于 = 和 LIKE,并且它仍然仅限于一个 WHERE 条件)。执行 WHERE 1 = 1 之类的操作来返回所有记录也感觉很奇怪。
WHERE $1 = $2
我很想听听人们对此的想法,或者是否有更好的方法。
【问题讨论】:
标签: node.js postgresql pg-promise