登录
首页 >  Golang >  Go问答

在postgresql的where子句中是否可以不指定字段?

来源:stackoverflow

时间:2024-03-24 14:00:39 407浏览 收藏

在 PostgreSQL 的 WHERE 子句中,可以根据指定字段是否为空字符串来有条件地排除该字段。如果字段为空,则从 WHERE 子句中排除,仅选择与其他匹配字段匹配的记录。此功能可用于灵活查询,在其中某些字段可能为空或未知。

问题内容

在 sql 中我有以下代码:

-- name: FilterRecords :many
SELECT *
FROM records
WHERE industry_id = $3 and region_code = $4 and city_code = $5
OFFSET $1 LIMIT $2;

我想要实现的是,如果提供的值为空字符串,则从 where 子句中排除 industry_id 。因为当我进行查询时,它会计算空白字符串,但如果它是空白,我想忽略它,并仅选择与region_code和city_code匹配的记录。


正确答案


这是为我制作的并且工作正常。

-- name: filterapz :many
select *
from apz
where industry_id like coalesce(nullif($3, ''), '%%') and region_code = $4 and city_code = $5
offset $1 limit $2;

你可以通过golang默认的text/template来做到这一点。

variables := map[string]interface{} {
    "industry_id": ...,
    "region_id": ...,
    "city_code": ...,
    "offset": ...,
    "limit": ...,
}

qs := new(strings.Builder)

template.Must(template.New("qt").Parse(`
SELECT *
FROM records where
    {{ if .industry_id-}} industry_id= {{.industry_id}} and {{- end }}
    region_code = {{.region_code}} and city_code = {{.city_code}}
OFFSET {{.offset}} LIMIT {{.limit}}`)).
        Execute(qs, variables)

fmt.Printf("qs: %v\n", qs.String())

本篇关于《在postgresql的where子句中是否可以不指定字段?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>