Golang SQL包的jsonb运算符

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

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}' or
  • WHERE 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_objectjson_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}';

huangapple
  • 本文由 发表于 2015年9月19日 07:27:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/32662478.html
匿名

发表评论

匿名网友

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

确定