PostgreSQL中如何从JSON文本提取哈希数组键值并逗号分隔展示?
Got it, let's get that query working exactly how you need it. The issue with your current statement is that you're pulling the entire genres array instead of extracting just the text values and combining them. Here's how to fix it:
Step-by-Step Breakdown
Since your data field is stored as text, we'll first cast it to jsonb (it’s more efficient for array operations than plain json) and then:
- Use
jsonb_array_elementsto "unpack" thegenresarray into individual rows, each holding one genre object - Extract the
textvalue from each genre object using->>'text'(the double arrow returns a plain text string instead of a JSON value) - Use
string_aggto stitch all the genre texts into a single comma-separated string - Group by the book’s
idto ensure each book gets one row with its combined genres
Final Working Query
SELECT id, string_agg(genre->>'text', ',') AS genre_list FROM books, jsonb_array_elements((data::jsonb)->'genres') AS genre WHERE (data::jsonb)->'genres' IS NOT NULL GROUP BY id LIMIT 1;
Handling Edge Cases
If some books might have an empty genres array or the field is null, use COALESCE to return a clean default value (like an empty string) instead of null:
SELECT id, COALESCE(string_agg(genre->>'text', ','), '') AS genre_list FROM books, jsonb_array_elements((data::jsonb)->'genres') AS genre GROUP BY id LIMIT 1;
Example Output
For your sample data {"genres":[{"text":"Crime","id": "1"},{"text":"Romance","id": "5"}],"name":"Harry Potter"}, this query will return:
| id | genre_list |
|---|---|
| 1 | Crime,Romance |
内容的提问来源于stack exchange,提问作者Surya

