[英]Postgres/Sequelize - Append clause in a query conditionally
我有一個有一些記錄的表。 我必須在 2 個日期之間或在給定日期之后/之前過濾這些記錄,或者如果沒有通過日期則根本不過濾。 日期來自服務器路由有效負載。 查詢是這樣的:
select * from table where "id"=4 and (s2."createdAt" >= date("createdAt") and s2."createdAt" <= date("createdAt"))
在這里,可以給出第一個createdAt
,或者給出第二個,或者根本沒有,如果查詢沒有 and 子句並且將在"id"=4
。 我正在使用 sequelize 編寫原始查詢和 JavaScript/NodeJS 以進行實現。 這是代碼:
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")`);
目前,我正在編寫 4 個不同的 if/else 案例,其中包含 4 個針對日期可用性的不同查詢。 如何通過僅定義一個查詢並附加日期(如果可用)來使其動態化?
你可以這樣做:
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)
這可以縮短為:
where
id = :user_id
and s2."createdAt" >= coalesce(:param_from_date, s2."createdAt")
and s2."createdAt" <= coalesce(:param_to_date, s2."createdAt")
請注意,這些表達式使用查詢參數而不是查詢字符串中的混合值。 您確實希望使用參數化查詢來保護您的查詢免受 SQL 注入並使其更高效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.