简体   繁体   中英

Postgres query json data

I currently have a PostgreSQL table that looks something like this, the data column is JSON, I am trying to query the table based on keys that may or may not be in the JSON data.

    | A | B | C |            data                      |
    ----------------------------------------------------
    | 1 | 2 | 3 | {}                                   |
    | 2 | 3 | 3 | {"name": "jack", "message": "123"} |
    | 3 | 4 | 3 | {"name": "jill", "voice": "456"}   |
    | 4 | 2 | 3 | {"name": "bill", "email" "789"}   |

Currently I have

    SELECT *
    FROM (
    SELECT
     a,
     b,
     c,
     coalesce(
         CASE
         WHEN (data ->> 'message') IS NULL
           THEN NULL
         ELSE (data ->> 'message')
         END,
         '') AS message,
     coalesce(
         CASE
         WHEN (data ->> 'voice') IS NULL
           THEN NULL
         ELSE (data ->> 'voice')
         END,
         '') AS voice,
     coalesce(
         CASE
         WHEN (data ->> 'email') IS NULL
           THEN NULL
         ELSE (data ->> 'email')
         END,
         '') AS email
   FROM mytable) AS t
    WHERE (t.message = "789" OR
           t.voice = "789" OR
           t.email = "789");

I am currently getting the error, ERROR: column "789" does not exist

I know there is probably a more efficient way of doing it. Any help greatly appreciated.

使用单引号t.message = '789'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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