You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 the medica object inside the scores JSONB column (returns a JSONB object).
  • ->'categories': Drills down further into the categories nested object (still JSONB).
  • ->>domain_name: Uses the value from the domain_name column 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:

iddomain_namedomain_score
1food_insecuritylow
2housinghigh

内容的提问来源于stack exchange,提问作者Mateusz Urbański

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:41:38