代码之家  ›  专栏  ›  技术社区  ›  Erik Strömberg

PostgreSQL中JSON数组中存在密钥

  •  2
  • Erik Strömberg  · 技术社区  · 9 年前

    我有一个问题,我不太明白。

    假设我有一个名为电影的专栏,看起来像这样(jsonb):

    [{"title": "Pulp Fiction"}, {"tiitle": "Rambo"}]
    

    有没有一种方法可以找到电影中带有tititle键的对象的行?

    1 回复  |  直到 9 年前
        1
  •  0
  •   Community CDub    8 年前

    对于Postgres 9.4:

    ds=# CREATE TABLE yourtable (movie jsonb);
    CREATE TABLE
    ds=# \d+ yourtable 
                          Table "public.yourtable"
     Column | Type  | Modifiers | Storage  | Stats target | Description 
    --------+-------+-----------+----------+--------------+-------------
     movie  | jsonb |           | extended |              | 
    
    ds=# INSERT INTO yourtable VALUES ('[{"title": "Pulp Fiction"}, {"tiitle": "Rambo"}]');
    INSERT 0 1
    
    ds=# SELECT * FROM yourtable yt,jsonb_array_elements(yt.movies) AS movie
    WHERE movie ? 'tiitle';
    

    SO有很多 good resources 与Postgres一起 documentation .