[英]postgres to query count when json value is match LIKE condition
I have mssql query which works to query the json data which kept in database column like below:我有 mssql 查询,它可以查询保存在数据库列中的 json 数据,如下所示:
SELECT COUNT(*) as count FROM t1.test where lower(data) LIKE '%state':'new%'
{
"id": "DO-Test CC1",
"state": "NEW",
"type": "Test type",
"items": [
{
"itemReports": [],
"id": "066c7499-a4b6-4346-ac98-6a71d0ddfc36",
"itemId": "Augmentn New",
"quantity": 100,
"dispenseAsWritten": false,
"administrationInstructions": "123"
}
]
}
It does not work when i run it at pgAdmin (postgres database).当我在 pgAdmin(postgres 数据库)上运行它时它不起作用。
i am using Docker version 19.03.4, build 9013bf5我正在使用 Docker 版本 19.03.4,构建 9013bf5
which syntax should be replaced?应该替换哪种语法?
You don't need to use like
or anything similar.您不需要使用like
或任何类似的东西。 You can use ->>
to access the value of a key.您可以使用->>
访问键的值。 If you don't know if it's upper or lower case, you can apply a lower() on the result of that expression:如果您不知道它是大写还是小写,您可以对该表达式的结果应用lower():
SELECT COUNT(*) as count
FROM t1.test
where lower(data ->> 'state') = 'new';
If the column is defined as jsonb
(which it should be) and you have a GIN index on the data
column and you are sure that the state is always upper case, the following is probably more efficient:如果该列被定义为jsonb
(它应该是)并且您在data
列上有一个 GIN 索引并且您确定状态总是大写,那么以下可能更有效:
SELECT COUNT(*) as count
FROM t1.test
where data @> '{"state": "NEW"}'
Update as you don't store your JSON in a jsonb
column (which you should do), you need to cast the column to jsonb
in order to be able to use the functions, eg更新,因为您没有将 JSON 存储在jsonb
列中(您应该这样做),您需要将该列转换为jsonb
以便能够使用这些功能,例如
where lower(data::jsonb ->> 'state') = 'new';
or或者
where data::jsonb @> '{"state": "NEW"}
But you should really consider to change that column to jsonb
rather than varchar
但是您真的应该考虑将该列更改为jsonb
而不是varchar
You can use the ->>
JSON operator to access state
's value as text
.您可以使用->>
JSON 运算符以text
访问state
的值。
SELECT ...
FROM ...
WHERE data->>'state' = 'NEW';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.