PostgreSQL中利用其他列从JSONB字段获取数据的SQL查询需求
PostgreSQL: Fetch JSONB Data Matching
domain_name Column Value Got it, let's tackle this problem. You need to dynamically pull the value from the scores JSONB column that corresponds to the value in the domain_name column—PostgreSQL's JSONB operators make this straightforward.
Solution Query
Here's the SQL that does exactly what you need:
SELECT id, domain_name, -- Extract the text value matching the domain_name scores->'medica'->'categories'->>domain_name AS domain_score FROM survey_results;
How It Works
Let's break down the JSONB operations step by step:
scores->'medica': Navigates to themedicaobject inside thescoresJSONB column (returns a JSONB object).->'categories': Drills down further into thecategoriesnested object (still JSONB).->>domain_name: Uses the value from thedomain_namecolumn as the dynamic key to extract the corresponding text value. The->>operator returns a text string instead of a JSONB type, which is usually what you want for direct use in reports or further processing.
If You Need JSONB Instead of Text
If you want to keep the result as a JSONB value (instead of plain text), swap ->> with ->:
SELECT id, domain_name, scores->'medica'->'categories'->domain_name AS domain_score_json FROM survey_results;
Expected Output
For your sample data, the first query will return:
| id | domain_name | domain_score |
|---|---|---|
| 1 | food_insecurity | low |
| 2 | housing | high |
内容的提问来源于stack exchange,提问作者Mateusz Urbański
相关产品推荐
相关产品推荐

