简体   繁体   English

如何过滤 Postgresql 中的 JSON 列?

[英]How can I filter JSON column in Postgresql?

Lets say that we have simple table,假设我们有简单的表格,

  • id - user id id - 用户 ID
  • rooms - number of rooms which the user is searching in JSON type. rooms - 用户在 JSON 类型中搜索的房间数。
id rooms
1 ["3.0","4.0"]
2 ["3.0"]
3 ["1.0"]

How can I filter for example user id which is searching 3 rooms?如何过滤例如正在搜索 3 个房间的用户 ID?

I know that code like:我知道这样的代码:

SELECT
    id
FROM 
    example_column
WHERE
rooms::text LIKE '%3.0%'

is working, but i'm lookig for more gentle method.正在工作,但我正在寻找更温和的方法。

You can use the "exists" ?你可以使用“存在” ? operator to test for elements in an array:运算符来测试数组中的元素:

SELECT id
FROM the_table
WHERE rooms ? '3.0';

The operator is only available for jsonb values, if you are really using a json column, you need to cast it:该运算符仅适用于jsonb值,如果您真的使用json列,则需要对其进行转换:

WHERE rooms::jsonb ? '3.0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM