【发布时间】:2018-11-03 12:21:12
【问题描述】:
我有一张如下表
date | tags
------------+----------------------------------------------------------------------------------------------------------
2018-10-24 | {"table": "bank_trans", "metric": "withdrawal", "location": "UK"}
2018-10-24 | {"table": "bank_trans", "metric": "balance", "account_id": "477", "location": "ny", "country": "USA"}
2018-10-24 | {"table": "bank_trans", "metric": "deposit", "location": "blr", "country": "IND"}
2018-11-02 | {"table": "bank_trans", "metric": "balance", "account_id": "477"}
如果我想要包含如下搜索模式的特定行
select date, tags
from webhook_forecastmodel
where tags LIKE '%"table": "bank_trans"%' AND
tags LIKE '%"metric": "balance"%' AND
tags LIKE '%"account_id": "477"%';
在这种情况下,我得到两个结果
date | tags
------------+----------------------------------------------------------------------------------------------------------
2018-10-24 | {"table": "bank_trans", "metric": "balance", "account_id": "477", "location": "ny", "country": "USA"}
2018-11-02 | {"table": "bank_trans", "metric": "balance", "account_id": "477"}
我了解 SQL 查询会返回与模式匹配的行。
但我只想要LIKE 搜索模式中确切提到的行,即"table": "bank_trans"、"metric": "balance" 和"account_id": "477",这让我们只剩下一行
2018-11-02 | {"table": "bank_trans", "metric": "balance", "account_id": "477"}
有什么方法可以实现吗?
【问题讨论】:
-
如果列的数据类型为
json,则使用json函数和运算符,而不是like -
修复你的数据结构!不要将字符串视为 JSON。更重要的是,将值放在应该在列中的列中;不要将它们存储在字符串中。
-
PostgreSQL 支持 JSON 作为列类型。如果它在 JSON 列中并使用 JSON 函数,而不是尝试在字符串上使用模式匹配或将数据规范化为结构,这会简单得多。
标签: sql postgresql sql-like postgresql-9.2