我在postgres表中有一个jsonb列,其中包含以下数据..
1. {"age": {"toage": "", "fromage": ""}, "sex": [], "hometown": [],
"occupation": [], "destination": [], "nationality": [244, 245, 247],
"travelpurpose": [], "currentlocation": []}
2. {"age": {"toage": "45", "fromage": "25"}, "sex": [1, 2], "hometown":
[386, 336, 337, 339, 389, 424, 453, 457, 471, 475, 377, 413,460,
387, 458, 287, 341, 372, 2783], "occupation": [15, 17, 25, 27],
"destination": [377, 413, 460, 387], "nationality": [340, 435],
"travelpurpose": [5, 6], "currentlocation": []}
3. {"age": {"toage": "45", "fromage": "25"}, "sex": [1, 2], "hometown":
[386, 336, 337, 339, 389, 424, 453, 457, 471, 475, 377, 413,460,
387, 458, 287, 341, 372, 2783], "occupation": [15, 17, 25, 27],
"destination": [377, 413, 460, 387], "nationality": [340, 435],
"travelpurpose": [5, 6], "currentlocation": []}
4. {"age": {"toage": "", "fromage": ""}, "sex": [], "hometown": [],
"occupation": [], "destination": [], "nationality": [],
"travelpurpose": [], "currentlocation": []}
我需要查询jsonb中的数组。
为此我正在使用以下查询。
SELECT * FROM campaign
where target_demographics @> '{"sex": [1], "hometown": [337],"occupation":[], "destination": [], "nationality": [], "travelpurpose": [], "currentlocation": []}';
将匹配2和3 jsonb cloumns。但我需要的是它也应该匹配1和2。
意思是,只检查包含我还需要的内容,如果指定的数组为空,它也应该返回。
有没有办法做到这一点postgres9.4 ????
更新:
为此我已经按照下面的查询来检查每个字段。这是正确的方法。或者还有其他更好的方法来做到这一点。
SELECT campaignid,target_demographics FROM campaign where ((target_demographics ::json#>>'{age,fromage}') ='' or (target_demographics ::json#>>'{age,fromage}')<='30') and ((target_demographics ::json#>>'{age,toage}') ='' or(target_demographics ::json#>>'{age,toage}')>='30') and (target_demographics @> '{"sex": []}' or target_demographics @> '{"sex": [1]}') and (target_demographics @> '{"hometown": []}' or target_demographics @> '{"hometown": [337]}') and (target_demographics @> '{"occupation": []}' or target_demographics @> '{"occupation": [25]}') and (target_demographics @> '{"destination": []}' or target_demographics @> '{"destination": [377]}') and (target_demographics @> '{"nationality": []}' or target_demographics @> '{"nationality": [244]}') and (target_demographics @> '{"travelpurpose": []}' or target_demographics @> '{"travelpurpose": [6]}') and (target_demographics @> '{"currentlocation": []}' or target_demographics @> '{"currentlocation": []}');