比较 SQL 的日期列与日期。

huangapple go评论82阅读模式
英文:

Compare SQL date column with date

问题

假设我将日期列的值插入为:

TO_DATE('06/08/2021', 'DD/MM/YYYY')

我想在 Golang 中将此列 valid_till 进行比较,代码如下:

_err := database.GetDbReadClient().Raw("SELECT * from base_configs  WHERE tenant = ? AND valid_till <= ?", tenant, time.Now()).Scan(&baseConfig).Error

time.Now() 无法工作。但是我不知道如何比较日期。

我的在 Postgres 中的插入是否正确?
如果正确,我应该用什么来替代 time.Now() 来与 valid_till 列进行比较?

英文:

Suppose I inserted the date column value as

 TO_DATE(&#39;06/08/2021&#39;, &#39;DD/MM/YYYY&#39;)

I want to compare this column valid_till in Golang as

_err := database.GetDbReadClient().Raw(&quot;SELECT * from base_configs  WHERE tenant = ? AND valid_till &lt;= ?&quot;, tenant, time.Now()).Scan(&amp;baseConfig).Error

time.Now() won't work. But I am not getting around how to go about it to compare dates.

Is my insertion in Postgres correct?
If so, what can I write instead of time.Now to compare it with valid_tillcolumn?

答案1

得分: 1

你可以将参数转换为原始 SQL 中的 date 类型。

raw := `SELECT * FROM base_configs
WHERE tenant = ?
AND valid_till <= ?::date`

err := database.GetDbReadClient().Raw(raw, tenant, time.Now()).Scan(&baseConfig).Error

或者将 time.Time 实例格式化为日期字符串。

raw := `SELECT * FROM base_configs
WHERE tenant = ?
AND valid_till <= ?`

date := time.Now().Format("02/01/2006")
err := database.GetDbReadClient().Raw(raw, tenant, date).Scan(&baseConfig).Error
英文:

You could cast the parameter to the date type in the raw SQL.

raw := `SELECT * FROM base_configs
WHERE tenant = ?
AND valid_till &lt;= ?::date`

err := database.GetDbReadClient().Raw(raw, tenant, time.Now()).Scan(&amp;baseConfig).Error

Or just format the time.Time instance as a date string.

raw := `SELECT * FROM base_configs
WHERE tenant = ?
AND valid_till &lt;= ?`

date := time.Now().Format(&quot;02/01/2006&quot;)
err := database.GetDbReadClient().Raw(raw, tenant, date).Scan(&amp;baseConfig).Error

huangapple
  • 本文由 发表于 2021年8月6日 15:26:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/68677720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定