简体   繁体   English

Postgres/Sequelize - 有条件地在查询中追加子句

[英]Postgres/Sequelize - Append clause in a query conditionally

I have a Table which has some records.我有一个有一些记录的表。 I have to filter those records between 2 dates or after/before a given date, or no filter at all if no dates are passed.我必须在 2 个日期之间或在给定日期之后/之前过滤这些记录,或者如果没有通过日期则根本不过滤。 Dates are coming by server route payload.日期来自服务器路由有效负载。 Query is something like this:查询是这样的:

select * from table where "id"=4 and (s2."createdAt" >= date("createdAt") and s2."createdAt" <= date("createdAt"))

Here, either first createdAt may be given, or second, or none at all in case of which the query wouldn't have and clause and will complete at "id"=4 .在这里,可以给出第一个createdAt ,或者给出第二个,或者根本没有,如果查询没有 and 子句并且将在"id"=4 I am using sequelize to write the raw query and JavaScript/NodeJS for implementation.我正在使用 sequelize 编写原始查询和 JavaScript/NodeJS 以进行实现。 Here is the code:这是代码:

 query = await sequelize.query(`select * from "Stores" s2 where "Id" = ${user.id} and (s2."createdAt" >='${param.fromDate}' and s2."createdAt <='${param.toDate}') group by date("createdAt")`);

Currently, i am writing 4 different if/else cases with 4 different queries respective to availability of date.目前,我正在编写 4 个不同的 if/else 案例,其中包含 4 个针对日期可用性的不同查询。 How can i have it dynamic by defining just one query and appending dates if available?如何通过仅定义一个查询并附加日期(如果可用)来使其动态化?

You could do:你可以这样做:

where 
    id = :user.id
    and (:param_from_date is null or s2."createdAt" >= :param_from_date)
    and (:param_to_date is null   or s2."createdAt" <= :param_to_date)

This can be shortened as:这可以缩短为:

where 
    id = :user_id
    and s2."createdAt" >= coalesce(:param_from_date, s2."createdAt")
    and s2."createdAt" <= coalesce(:param_to_date, s2."createdAt")

Note that these expressions use query parameters instead of mungling values in the query string.请注意,这些表达式使用查询参数而不是查询字符串中的混合值。 You do want to use parameterized query to protect your queries againts SQL injection and make them more efficient.您确实希望使用参数化查询来保护您的查询免受 SQL 注入并使其更高效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM