mysql - postgresql 中的 JSON_CONTAINS()

标签 mysql postgresql laravel

使用 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

我的 table :

  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 一起使用。

最佳答案

您引用的 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;

关于mysql - postgresql 中的 JSON_CONTAINS(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41248082/

相关文章:

php - 无法在 view.Laravel 中获取值

MySQL 带有别名的多个 UNION

python - MySQL 查询参数的数量与传递给执行的参数匹配,但 Python 引发 "not all arguments converted"

php - 在 for 循环中运行 mysql 查询的意外 T_STRING

postgresql - 默认为 LATIN1 编码的语言环境

sql - 如何将 WITHIN GROUP 从 Oracle 翻译成 Postgres?

java - 是否可以在没有列的情况下在 JPA/Hibernate 中创建和使用序列生成器?

PHP7 - nusoap - nusoap_client 有一个弃用的构造函数

laravel - session.php 中 laravel 生命周期配置变量的最大可能值是多少

php - 比较两行中的列,以及另一列的不同更改值