英文:
Golang SQL package jsonb operator
问题
在PostgreSQL的sql包中,如何使用@>
运算符与字符串查询一起使用,例如:
WHERE data @> '{"stringdata": $1}'
或者WHERE data @> '{"stringdata": "$1"}'
不起作用
替代方法是 data->>'string_data' = $1
,但我不喜欢使用多个语句
错误信息为:
"Message": "invalid input syntax for type json",
"Detail": "Token \"$\" is invalid.",
"Where": "JSON data, line 1: $...",
"Routine": "report_invalid_token"
英文:
In sql package for postgresql jsonb how can I use the @>
operator with a string query for example
WHERE data @> '{"stringdata": $1}'
orWHERE data @> '{"stringdata": "$1"}'
doesn’t work
The alternative is data->>'string_data' = $1
which I don’t prefer for multiple statements
Error is:
"Message": "invalid input syntax for type json",
"Detail": "Token \"$\" is invalid.”,
"Where": "JSON data, line 1: $...",
"Routine": "report_invalid_token"
答案1
得分: 4
据我所知,你不能在字符串内进行插值,但是你可以使用json_build_object
或json_object
来构建一个JSON对象:
SELECT data FROM test
WHERE data @> json_build_object('stringdata', $1::text, 'foo', $2::int)::jsonb;
这基本上相当于:
SELECT data FROM test
WHERE data @> '{"stringdata":"$1","foo":$2}';
希望对你有帮助!
英文:
AFAIK, you can't interpolate inside strings, but you can build a JSON object using json_build_object
or json_object
:
SELECT data FROM test
WHERE data @> json_build_object('stringdata', $1::text, 'foo', $2::int)::jsonb;
This is basically an equivalent of
SELECT data FROM test
WHERE data @> '{"stringdata":"$1","foo":$2}';
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论