2

Using MySQL 5.7, I want to know the PostgreSQL equivalent of

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

How do you write JSON_CONTAINS(users, JSON_ARRAY(1)) in PostgreSQL

EDIT 1

there is my json it's just an array without son object :

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

i want to get "doe" for exemple

EDIT 2

My 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 |                 

EDIT 3: I use laravel to execute queries :

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

and it's work with mysql.

yecir
  • 21
  • 1
  • 3

1 Answers1

3

The two argument form of MySQL's JSON_CONTAINS() you cite has a signature of JSON_CONTAINS(json_doc, val) That sounds similar to the PostgreSQL JSON operator @> 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"]';

If your type is json, that's fine just cast it to jsonb;

SELECT *
FROM user_conversations
WHERE users::jsonb @> json_text;
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468