2016-07-11 3 views
0

기본적으로 jsonb 유형의 열이있는 postgresql 테이블이 있습니다. JSON 데이터가 내 PostgreSQL의 명령 줄에서 "화성"과 "테란"국적 ..이 모든 사람을 인출 할이postgresql에서 jsonb 열을 검색하는 방법

{ 
    "personal": { 
    { 
     "gender":"male", 
     "contact":{ 
      "home":{ 
      "email":"[email protected]", 
      "phone_number":"5551234" 
      }, 
      "work":{ 
      "email":"[email protected]", 
      "phone_number":"5551111" 
      } 
     }, 
     "religion":"other", 
     "languages":[ 
      "English", 
      "Xen" 
     ], 
     "last_name":"Eeo", 
     "birth_date":"1945-07-28", 
     "first_name":"Cee", 
     "nationality":"Martian", 
     "marital_status":"married" 
    } 
    } 
} 

처럼 보이는이이 작품

select employees->'personal'->'contact'->'work'->'email' 
from employees 
where employees->'personal' @> '{"nationality":"Martian"}' 
    or employees->'personal' @> '{"nationality":"Terran"}' 

작동 .. 그러나 그것은 추한 ... 나는이 같은 실행하려는 :

select employees->'personal'->'contact'->'work'->'email' 
from employees 
where employees->'personal'->'nationality' in ('Martian','Terran') 

을하지만이 같은 서식 오류를 얻을 :

DETAIL: Token "Martian" is invalid. 
CONTEXT: JSON data, line 1: Martian 

답변

1

는이 일어날 수 있도록하기 위해 "텍스트로 값을 얻을"연산자 ->>를 사용해야합니다 : 당신이 텍스트로한다고 가정하기 때문에

select employees->'personal'->'contact'->'work'->>'email' 
from employees 
where employees->'personal'->>'nationality' in ('Martian','Terran') 

내가 또한 이메일을 받고에 추가.

텍스트를 (employees->'personal'->'nationality')::text으로 캐스팅하는 것은 값만 반환하지만 텍스트로 변환 된 json은이 경우에는 "Martian"이며 따옴표가 포함되어 있기 때문에 작동하지 않습니다.

+0

새로운 질문 (관련) http://stackoverflow.com/questions/38324360/how-to-use-postgresql-any-with-jsonb-data – abbood

1

사용 ->> operator :

select employees->'personal'->'contact'->'work'->'email' 
from employees 
where employees->'personal'->>'nationality' in ('Martian','Terran') 
관련 문제