【问题标题】:JSON_CONTAINS() in postgresqlpostgresql 中的 JSON_CONTAINS()
【发布时间】:2017-05-06 00:13:46
【问题描述】:

使用 MySQL 5.7,我想知道 PostgreSQL 相当于

SELECT * FROM user_conversations WHERE JSON_CONTAINS(users, JSON_ARRAY(1))

JSON_CONTAINS(users, JSON_ARRAY(1)) 在 PostgreSQL 中怎么写

编辑 1

这是我的 json 它只是一个没有子对象的数组:

[
 "john", 
 "doe", 
 "does"
]

我想以“doe”为例

编辑 2

我的桌子:

  Column   |              Type              |                     Modifiers                     | Storage | Statistics Target | Description 
 ------------+--------------------------------+-------------------------------------------------------+----------+-----------------------+-------------
  id         | uuid                           | non NULL                                                   | plain    |                       | 
  name       | character varying(255)         | non NULL                                              | extended |                       | 
  image      | character varying(255)         | non NULL Par défaut, 'default.png'::character varying | extended |                       | 
  users      | json                          | non NULL                                              | extended |                       | 
  type       | integer                        | non NULL                                              | plain    |                       | 
  emoji_id   | integer                        | non NULL Par défaut, 0                                | plain    |                       | 
  created_at | timestamp(0) without time zone |                                                       | plain    |                       | 
  updated_at | timestamp(0) without time zone |                 

编辑 3: 我使用 laravel 执行查询:

DB::table('user_conversations')->whereRaw('JSON_CONTAINS(users, JSON_ARRAY(1))')->orderBy('created_at', 'desc')->paginate(5);

它适用于 mysql。

【问题讨论】:

  • 你看过library。顺便说一句,我从来没有使用过 mysql 版本,也没有使用过这个 pgsql 版本。只是认为这可能是一个不错的起点
  • This question 也可能是你的票
  • 你能粘贴user_conversations的架构吗?
  • @EvanCarroll 查看我的最后编辑

标签: mysql postgresql laravel


【解决方案1】:

你引用的 MySQL 的 JSON_CONTAINS() 的两个参数形式的签名是 JSON_CONTAINS(json_doc, val) 这听起来类似于 PostgreSQL JSON operator @> 运算符

-- returns true
SELECT '["john","bob","doe","dylan","mike","does"]'::jsonb @>
  '["john","doe","does"]';

-- returns false
SELECT '["john","bob","doe","dylan","mike","does"]'::jsonb @>
  '["john","mary"]';

如果您的类型是 json,那没关系,只需将其转换为 jsonb

SELECT *
FROM user_conversations
WHERE users::jsonb @> json_text;

【讨论】:

  • 我使用的是 json 类型而不是 jsonb
  • @yecir 你不应该,但它的工作原理相同,更新了答案。
  • 但我想要:从表中选择 *(json 列)
  • 我不确定,不清楚你在问什么。 JSON 是一个经过验证的文本列。 JSONB 是一种可以操作的二进制类型。文本必须变成二进制才能对其进行操作。
  • SELECT * FROM user_conversations WHERE users::jsonb @> "4411167c-4af8-39e8-b49a-85de76dc38cb";错误:列 « 4411167c-4af8-39e8-b49a-85de76dc38cb » 不存在
猜你喜欢
  • 2019-02-04
  • 2019-01-24
  • 2021-03-07
  • 2017-09-01
  • 2020-05-21
  • 2023-03-18
  • 2019-06-28
  • 2017-11-01
  • 2020-04-19
相关资源
最近更新 更多