This article describes how to extract value jsonb type of a key field in the PostGreSql
Reference: https://www.cnblogs.com/mywebnumber/p/5551092.html
First, the simple mode
- only one{}
# rule_config 字段格式 { "cardType": 1, "sellPrice": null, "originPrice": 15 } # 获取cardType SELECT rule_config -> 'cardType' AS cardType FROM t_free_ride_card_rule_config WHERE title = '测试0211'
- only one[]
# Rule_config Field Format [ "ZERO", "One", "TWO" ] # Get the first element of the SELECT rule_confi G -> 0 the AS the cardType the FROM t_free_ride_card_rule_config the WHERE title = '0211 test'
- Two parallel {}
# rule_config字段格式 [ { "ruleGuid": "1125720873758932994", "mcardType": 1, "packStart": "2020-02-14", }, { "ruleGuid": "1073055433702576129", "mcardType": 1, "packExpire": "2020-02-18" } ] # 获取key为ruleGuid 和 ruleGuid 的值 SELECT json_array_elements ( rule_config :: json ) -> 'ruleGuid' AS ruleGuid, json_array_elements ( rule_config :: json ) -> 'mcardType' AS mcardType FROM t_free_ride_card_rule_config WHERE title = '测试0211'
Second, complex formatting
- Data format jsonb
[ { "platform": 0, "cardPackage": [ { "ruleGuid": "1125720873758932994", "mcardType": 1, "packStart": "2020-02-14", "packExpire": "2020-02-15" }, { "ruleGuid": "1073055433702576129", "mcardType": 1, "packStart": "2020-02-16", "packExpire": "2020-02-18" } ], "platformExpire": "2020-02-18" } ]
- Sql get related fields
# 第一种,嵌套sql SELECT bottom :: json ->> 'ruleGuid' AS ruleGuid FROM ( SELECT json_array_elements ( cardPackage ) AS bottom FROM ( SELECT expire_info :: json -> 'cardPackage' AS cardPackage FROM ( SELECT expire_info :: json -> 0 AS expire_info FROM t_ev_month_card WHERE user_new_id = '1200107139' ) AS A ) AS B ) The AS F.
Description:
The first layer sql: the SELECT expire_info JSON :: -> 0 the AS expire_info the FROM t_ev_month_card the WHERE user_new_id = '1200107139' acquired an outermost {data}, a column named expire_info
second layer sql: from outermost curly braces expire_info acquired key = "cardPackage" content expire_info :: json -> 'cardPackage' , a column named cardPackage
third layer sql: column contents cardPackage {} into separate
fourth layer sql :} ruleGuid removed from each individual field {(see a, (1) section)# 第二种, SELECT (json_array_elements((expire_info -> 0):: json ->'cardPackage'))->'ruleGuid' AS a FROM t_ev_month_card WHERE user_new_id = '1200107139'
If the data type is jsonb, may be replaced json to jsonb:
SELECT bottom :: jsonb -> 'ruleGuid' AS ruleGuid FROM ( SELECT jsonb_array_elements ( cardPackage ) AS bottom FROM ( SELECT expire_info :: jsonb -> 'cardPackage' AS cardPackage FROM ( SELECT expire_info :: jsonb -> 0 AS expire_info FROM t_ev_month_card WHERE user_new_id = '1200107139' ) AS A ) AS B ) AS F